| Problem statement | Source code | Tags: Brute force
My first obstacle was reading the file, which was surprisingly non-trivial in Fortran. But that doesn't pertain to the problem.
So theoretically, we would need a key-value mapping from these IDs to their counts, and then get the top three counts and their corresponding IDs. Unfortunately Fortran has no built-in hashmap. Fortunately we can see that no ID exceeds 1000. Therefore we just store counts in an array.
Next, we want to get the top 3 counts. There are three approaches here. Assume we want the top count among possible IDs. The first is to sort the entries as a list of (ID, count) pairs, and grab the first elements—this is . The second is to use quickselect, which is . The third is a dumb solution, which is just to traverse the array 3 times, each time grabbing the top unchosen index. Because 3 is fix anyway (so , and quickselect also has a hidden constant) and this is just day 1, let's use the dumbest solution.
Fortran's maxloc does exactly what we need: find the index of the largest element. Better yet, it provides a mask argument, which allows us to remove the indices that are already selected.
Finally, we just print product(top).
If we just replace maxloc with minloc, we run into a minor problem because now it will report indices with count 0. Therefore we also need to change available = .true. to available = count > 0 so the non-existent IDs are never considered. Fortran is really expressive with arrays!