From 57655c6a21adce77d8cea70c7f6446b55b56bc7b Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Mon, 3 Dec 2018 21:31:06 -0800 Subject: [PATCH] [2018][ruby][4.x] speedrun --- 2018/ruby/day_04.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 2018/ruby/day_04.rb diff --git a/2018/ruby/day_04.rb b/2018/ruby/day_04.rb new file mode 100644 index 0000000..2d32a81 --- /dev/null +++ b/2018/ruby/day_04.rb @@ -0,0 +1,23 @@ +records = ARGF.read.chomp.lines.map(&:chomp).sort +# puts records + +stats = Hash.new {|h,k| h[k] = [] } + +guard = nil +fell_asleep_at = nil +records.each do |record| + if record =~ /\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}\] Guard \#(\d+) begins shift/ + guard = $1.to_i + elsif record =~ /\[\d{4}-\d{2}-\d{2} \d{2}:(\d{2})\] falls asleep/ + fell_asleep_at = $1.to_i + elsif record =~ /\[\d{4}-\d{2}-\d{2} \d{2}:(\d{2})\] wakes up/ + stats[guard] << (fell_asleep_at...$1.to_i) + else + p record + end +end + +guard, (minute, _) = stats.map {|k,v| + [k, v.flat_map(&:to_a).group_by {|x| x }.max_by {|_,v| v.count }] +}.max_by {|_,(_,v)| v.count } +p guard * minute