-
Notifications
You must be signed in to change notification settings - Fork 0
/
4b.rb
148 lines (114 loc) · 2.64 KB
/
4b.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
148
require 'time'
require 'pry'
input = File.readlines('./4.input')
puts "Total lines: #{input.length}"
class LogEntry
attr_reader :timestamp
def initialize(raw)
@raw = raw
@timestamp = Time.parse(raw.match(/\[(.+)\]/)[1])
end
def <=>(other)
self.timestamp <=> other.timestamp
end
def to_s
@raw
end
def new_guard
matches = @raw.match(/Guard #(.+) begins shift/)
return matches && Integer(matches[1])
end
def sleep?
@raw.match?(/falls asleep/)
end
def awoke?
@raw.match?(/wakes up/)
end
end
class Guard
attr_reader :total_minutes, :id, :minute_distribution
@@guards = {}
def self.all
@@guards.values.sort.reverse
end
def self.[](id)
if guard = @@guards[id]
return guard
end
@@guards[id] = Guard.new(id)
end
def initialize(id)
@id = id
@total_minutes = 0
@minute_distribution = Hash.new { 0 }
end
def sleep(time)
@sleeping = true
@sleep_started = time
end
def awake(time)
if !@sleeping
raise "wasn't sleeping"
end
duration = time - @sleep_started
@total_minutes += (duration.to_i / 60 + 1)
if @sleep_started.hour != time.hour
raise "mismatched hours"
end
(@sleep_started.min...time.min).to_a.each do |min|
@minute_distribution[min] += 1
end
@sleep_started = nil
end
def <=>(other)
sleepiest_minute_count <=> other.sleepiest_minute_count
end
def sleepiest_minute_count
minute_distribution[sleepiest_minute]
end
def sleepiest_minute
return if @minute_distribution.empty?
@minute_distribution.invert.sort.last.last
end
def to_s
"##{@id} total=#{@total_minutes}, sleepiest_minute=#{sleepiest_minute}, sleepiest_minute_count=#{sleepiest_minute_count}"
end
end
class GuardSet
def initialize
guards = {}
end
def add_sleep(guard, duration)
end
end
class GuardStats
def self.process(log_entries)
i = 0
guards = GuardSet.new
sleep_begun = nil
current_guard = nil
log_entries.each do |entry|
puts entry
if entry.new_guard
current_guard = Guard[entry.new_guard]
elsif entry.sleep?
current_guard.sleep(entry.timestamp)
elsif entry.awoke?
current_guard.awake(entry.timestamp)
puts current_guard if current_guard.id == 3323
else
puts entry
raise 'unknown state'
end
i += 1
end
puts "Total processed: #{i}"
end
end
entries = input.map {|line| LogEntry.new(line) }
entries.sort!
GuardStats.process(entries)
puts Guard.all
sleepiest = Guard.all.first
puts "Sleepiest: #{sleepiest}"
puts "Result #{sleepiest.id * sleepiest.sleepiest_minute}"