-
Notifications
You must be signed in to change notification settings - Fork 0
/
day19.rb
87 lines (71 loc) · 1.56 KB
/
day19.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
require 'pry'
require 'set'
rules, msgs = File.read('input.txt').split("\n\n").map { |x| x.split("\n") }
ors = Array.new(rules.length)
rules.each do |str|
/(\d+): (.*)/ =~ str
ors[$1.to_i] = $2
end
def recurse(ors, i)
rule = ors[i]
isltr = rule.match? /"."/
isor = rule.match? /.*\|.*/
return [rule[1]] if isltr
if isor
ret = []
rule.split("|").each do |s1|
c1 = s1.scan(/\d+/).map(&:to_i).map { |x| recurse(ors,x) }.reduce do |a,b|
a.product(b).map &:join
end
ret << c1
end
return ret.flatten
else
return recurse(ors, rule.to_i) unless rule.include?(" ")
return rule.scan(/\d+/).map(&:to_i).map { |x| recurse(ors,x) }.reduce do |a,b|
a.product(b).map &:join
end
end
return ret.flatten
end
valid = recurse(ors,0)
valid8 = recurse(ors,8)
valid42 = recurse(ors,42)
valid31 = recurse(ors,31)
count = 0
msgs.each do |msg|
if valid.include?(msg)
count += 1
puts msg
next
end
if msg.length % 8 == 0
msg_arr = msg.split('').each_slice(8).map(&:join)
next unless valid8.include?(msg_arr[0])
# need ending condition too
i = 0
count8 = 0
count31 = 0
while i < msg_arr.length
if valid8.include?(msg_arr[i])
count8+=1
i += 1
else
break
end
end
while true
if valid31.include?(msg_arr[i])
count31 += 1
i += 1
else
break
end
end
if count31 > 0 && count8 > count31 && count8 + count31 == msg_arr.length
count += 1
puts msg
end
end
end
puts count