Skip to content

Commit 218bfb0

Browse files
authored
Merge pull request #554 from spamegg1/patch-17
Solution article for 2024 Day 01
2 parents af27a5b + 731def2 commit 218bfb0

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

docs/2024/puzzles/day01.md

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,71 @@ import Solver from "../../../../../website/src/components/Solver.js"
22

33
# Day 1: Historian Hysteria
44

5+
by [@spamegg1](https://github.com/spamegg1)
6+
57
## Puzzle description
68

79
https://adventofcode.com/2024/day/1
810

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

1172
- [Solution](https://github.com/rmarbeck/advent2024/tree/main/day1) by [Raphaël Marbeck](https://github.com/rmarbeck)

0 commit comments

Comments
 (0)