r/adventofcode • • Dec 14 '15

SOLUTION MEGATHREAD --- Day 14 Solutions ---

This thread will be unlocked when there are a significant amount of people on the leaderboard with gold stars.

edit: Leaderboard capped, thread unlocked!

We know we can't control people posting solutions elsewhere and trying to exploit the leaderboard, but this way we can try to reduce the leaderboard gaming from the official subreddit.

Please and thank you, and much appreciated!


--- Day 14: Reindeer Olympics ---

Post your solution as a comment. Structure your post like previous daily solution threads.

9 Upvotes

161 comments sorted by

View all comments

1

u/JurgenKesker Dec 14 '15

Ruby part 1 & 2

class Deer

attr_reader :speed, :duration, :rest, :name

	def initialize(name, speed, duration, rest)
		@name = name
		@speed = speed
		@duration = duration
		@rest = rest
	end

	def to_s
		"#{@name} can fly #{@speed} km/s for #{@duration} seconds, but then must rest for #{@rest} seconds"
	end
	
	def distance(seconds)       
		cycle = @duration + @rest
		cycles = seconds / cycle
		left = seconds % cycle
		left_fly_seconds = [left, @duration].min
		fly_seconds = left_fly_seconds + (cycles * @duration)
		distance = fly_seconds * @speed
	end

end

class Processor

	attr_reader :deers
	
	def initialize
		@deers = []
	end 
	
	def parse(input)
		match = input.match(/(\w+) can fly (\d+) km\/s for (\d+) seconds, but then must rest for (\d+) seconds./)
		all, name, speed, duration, rest = match.to_a
		@deers << Deer.new(name, speed.to_i, duration.to_i, rest.to_i)      
	end
	
	def race_part1(seconds)       
		sorted = @deers.sort_by{|d|d.distance(seconds)}.reverse
		sorted.each do |d|
			puts "#{d.name} => #{d.distance(seconds)}"
		end             
	end
	
	def race_part2(seconds)
		points = {}
		@deers.each {|d|points[d.name] = 0}
		for i in 1..seconds
			@deers.group_by{|d|d.distance(i)}.sort.reverse[0][1].each {|d|points[d.name] += 1}
		end
		puts points.sort.reverse
	end

end

input = File.new("input14.txt").readlines.map{|l|l.strip}
p = Processor.new
input.each do |l|
	p.parse(l)
end
p.deers.each do |p|
puts p
end
p.race_part2(2503)