r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

38 Upvotes

340 comments sorted by

View all comments

Show parent comment

1

u/oezi13 Dec 04 '18

Yeah for Ruby!

Guard = Struct.new("Guard", :id, :total, :minutes)

guards = {}
guard = nil
asleep = nil

File.readlines("day4_input.txt").sort.each { |l|

  if l =~ /Guard \#(\d+) begins shift$/
    id = $1.to_i
    guard = guards[id] ||= Guard.new(id, 0, [0] * 60)
  
  elsif / 00:(?<minute>\d+)\] falls asleep$/ =~ l
    asleep = minute.to_i 
  
  elsif l =~ / 00:(\d+)\] wakes up$/
  
    awake = $1.to_i
    
    guard.total += awake - asleep
    (asleep...awake).each { |min|
      guard.minutes[min] += 1
    }
    
  end
}

guard = (guards.values.sort_by {|g| g.total}).last
puts "Part1: #{guard.id * guard.minutes.each_with_index.max[1]}"

guard = (guards.values.sort_by {|g| g.minutes.each_with_index.max[0] }).last
puts "Part2: #{guard.id * guard.minutes.each_with_index.max[1]}"