-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16-2.rb
executable file
·147 lines (126 loc) · 2.63 KB
/
16-2.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env ruby
class Packet
attr_accessor :version
attr_accessor :type
def initialize(version, type)
@version = version
@type = type
end
end
class Literal < Packet
attr_accessor :data
def initialize(version, type)
raise "Literal with type #{type}" if type != 4
super(version, type)
@data = -1
end
def parse(bits)
bin = ''
loop do
group = bits.shift(5)
cont = group.shift.to_i(2)
bin += group.join
break if cont.zero?
end
@data = bin.to_i(2)
bits
end
def score
@data
end
end
class Operator < Packet
attr_accessor :sub_packets
def initialize(version, type)
super(version, type)
@type = type
@sub_packets = []
end
def parse(bits)
case length_type_id = bits.shift.to_i(2)
when 0
sub_packet_length = bits.shift(15).join.to_i(2)
@sub_packets = parse_packets bits.shift(sub_packet_length)
when 1
num_sub_packets = bits.shift(11).join.to_i(2)
num_sub_packets.times do
@sub_packets.append parse_packet(bits)
end
end
bits
end
end
class Sum < Operator
def score
@sub_packets.map(&:score).sum
end
end
class Product < Operator
def score
@sub_packets.map(&:score).reduce(1, :*)
end
end
class Minimum < Operator
def score
@sub_packets.map(&:score).min
end
end
class Maximum < Operator
def score
@sub_packets.map(&:score).max
end
end
class GreaterThan < Operator
def score
return 1 if @sub_packets[0].score > @sub_packets[1].score
0
end
end
class LessThan < Operator
def score
return 1 if @sub_packets[0].score < @sub_packets[1].score
0
end
end
class EqualTo < Operator
def score
return 1 if @sub_packets[0].score == @sub_packets[1].score
0
end
end
def parse_packet(bits)
version = bits.shift(3).join.to_i(2)
case type = bits.shift(3).join.to_i(2)
when 0
packet = Sum.new(version, type)
when 1
packet = Product.new(version, type)
when 2
packet = Minimum.new(version, type)
when 3
packet = Maximum.new(version, type)
when 4
packet = Literal.new(version, type)
when 5
packet = GreaterThan.new(version, type)
when 6
packet = LessThan.new(version, type)
when 7
packet = EqualTo.new(version, type)
else
raise "Unknown packet type #{type}"
end
packet.parse(bits)
packet
end
def parse_packets(bits)
packets = []
until bits.all? '0'
packets.append parse_packet(bits)
end
packets
end
packets = File.read('16.input').lines.map(&:strip).map { |l| l.split('').map { |c| c.to_i(16).to_s(2).rjust(4, '0').split '' }.flatten }
packets.each do |p|
print parse_packet(p).score, "\n"
end