November 03, 2023

Solution for Advent of Code 2015 - Day 14: Reindeer Olympics

Link to the puzzle text

Part 1

For this puzzle we have to simulate a reindeer race. Each reindeer flies for a period with a speed and then has to rest for another period. We are asked to find the reindeer leading the race after a time period.

For this, we calculate the number of combined rest and fly cycles for each reindeer. This is rounddown( race_length / (fly_duration + rest_duration)). In each of these period, the reindeer moves fly_duration * fly_speed units. The remaining time length is either spend fully or partly spend flying.

def race_distance(fly_speed, fly_duration, rest_duration, race_length):
distance = 0
num_periods = int(race_length / (fly_duration + rest_duration))
distance += num_periods * fly_speed * fly_duration
race_length -= num_periods * (fly_duration + rest_duration)
race_length = min(race_length, fly_duration)
distance += fly_speed * race_length
return distance

This calculation is repeated for each reindeer, since each has different values for fly_speed, fly_duration and rest_duration and the maximum of all distances is returned as the solution.

Part 2

For part 2, the scoring function is changed. Instead of just determining the winner at the end, we give a point of the leading reindeer at each point of the race.

There is probably a non-simulation way, but I instead iterated over the whole time period. For each reindeer, we track the current distance, status (flying or resting) and the time spent in that status. At each time step, for each reindeer we add the flying speed if we are in the flying state and check for state updates. After updating each reindeer, we award one point to the reindeer currently in the lead.

This is repeated for the whole race length and the winning reindeer and its highest points are returned as the solution.

No comments:

Post a Comment