Day 1: Dusty Shed
Puzzle Description
Scala Center Link
Scala Center Advent of Code 2026, Day 1
Full Solution Source
Solution Summary
- Parse input into list of numbers
- Count number of instances of each number
-
Get Result
- For Part 1, get 3 most common numbers
- For Part 2, get 3 least common numbers
Part 1
Let's start with parsing:
def parse(str: String): List[Int] = str.linesIterator.map(_.toInt).toList
Counting the number of instances is a really common task.
I have brain worms so I did it in a really complicated way, so I'll write that out here for completeness
// DONT USE! Easier way follows...
def count(ls: List[Int]): Map[Int, Int] =
ls.foldLeft(Map.empty[Int, Int]): (m, item) =>
m.updatedWith(item):
case Some(v) => Some(v + 1)
// I accidentally did 0 here, but because we are only counting how common a number is,
// this doesn't actually matter. You can set this to 1000 and it would still work.
case None => Some(1)
If you've perused the stdlib docs of List before you may know that the docs for groupMapReduce contain a recipe that does exactly what we need!
From groupMapReduce docs:
// renamed from occurrences => count, and specialized from generic to Int
def count(as: Seq[Int]): Map[Int, Int] =
as.groupMapReduce(identity)(_ => 1)(_ + _)
You can use either method, but it's better to have simpler code so I'll use the second method.
So for part 1, we need the 3 most common. For both cases I'll be using sortBy, but how we invoke it is different.
def part1(input: List[Int]): Int =
count(input).toList
.sortBy(_._2)(using Ordering[Int].reverse)
.take(3).map(_._2).product
To be optimized we're changing how we sort the list so that the most common entries come first, by reversing the ordering.
You could sort normally and use takeRight, or sort normally then reverse, but on linked lists both of these operations are really really slow! (Unsure on how slow, but I avoid them whenever possible).
Then we take the first 3 entries (which will be the most common thanks to the sort) and multiply them.
Part 2
Part 2, for some reason, is easier than part 1???????
Just drop the using argument from sortBy, and it JUST WORKS!
def part2(input: List[Int]): Int =
count(input).toList
.sortBy(_._2)
.take(3).map(_._2).product
The default implicit argument here is Ordering[Int] which, wouldn't you know, is the reverse of Ordering[Int].reverse! Amazing how that works.
Final Code
def parse(str: String): List[Int] = str.linesIterator.map(_.toInt).toList
def count(ls: List[Int]): Map[Int, Int] =
ls.groupMapReduce(identity)(_ => 1)(_ + _)
def part1(input: List[Int]): Int =
count(input).toList.sortBy(_._2)(using Ordering[Int].reverse).take(3)
.map(_._1).product
def part2(input: List[Int]): Int =
count(input).toList.sortBy(_._2).take(3).map(_._1).product