Skip to content

Commit cf8f487

Browse files
authored
Solution article for 2024 Day 01
- Also added link to my community solution
1 parent c338cb1 commit cf8f487

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

docs/2024/puzzles/day01.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,69 @@ import Solver from "../../../../../website/src/components/Solver.js"
66

77
https://adventofcode.com/2024/day/1
88

9+
## Solution Summary
10+
11+
1. Parse the input to split it into two lists (left/right), each sorted in increasing order.
12+
2. Find the distance scores (for `part1`) and the similarity scores (for `part2`).
13+
3. Sum the scores.
14+
15+
### Parsing
16+
17+
Our parser iterates over the lines, extracts the pair of numbers from each line,
18+
then splits them into two lists (lefts and rights), and separately sorts the lists.
19+
Therefore it looks like this:
20+
21+
```scala
22+
def parse(input: String): (Seq[Long], Seq[Long]) =
23+
// Extract pairs of numbers from each line
24+
val pairs = input
25+
.linesIterator
26+
.map(line => line.split(" ").map(_.toLong))
27+
.toSeq
28+
29+
// Group the left and right members from each pair, sort them
30+
val lefts = pairs.map(_.head).toSeq.sorted
31+
val rights = pairs.map(_.last).toSeq.sorted
32+
(lefts, rights)
33+
```
34+
35+
### Part 1
36+
37+
Now that the lefts and rights are sorted in increasing order, we can zip them,
38+
so that the first smallest on the left is paired with the first smallest on the right,
39+
the second smallest on the left is paired with the second smallest on the right, and so on.
40+
Then we can find the distances between them, and sum the distances:
41+
42+
```scala
43+
def part1(input: String): String =
44+
val (lefts, rights) = parse(input)
45+
lefts
46+
.zip(rights)
47+
.map((left, right) => math.abs(left - right)) // distances
48+
.sum
49+
end part1
50+
```
51+
52+
### Part 2
53+
54+
Very similar, but instead of distances, we find a left number's similarity on the right list.
55+
We do this by counting how many times the left number occurs on the right list,
56+
then multiply that count by the number itself.
57+
Finally we sum the similarity scores of all the left numbers:
58+
59+
```scala
60+
def part2(input: String): String =
61+
val (lefts, rights) = parse(input)
62+
lefts
63+
.map(left => rights.count(_ == left) * left) // similarity scores
64+
.sum
65+
end part2
66+
```
67+
68+
969
## Solutions from the community
1070

71+
- [Solution](https://github.com/spamegg1/aoc/blob/master/2024/01/01.worksheet.sc#L122) by [Spamegg](https://github.com/spamegg1/)
72+
1173
Share your solution to the Scala community by editing this page.
1274
You can even write the whole article! [See here for the expected format](https://github.com/scalacenter/scala-advent-of-code/discussions/424)

0 commit comments

Comments
 (0)