@@ -2,10 +2,71 @@ import Solver from "../../../../../website/src/components/Solver.js"
2
2
3
3
# Day 1: Historian Hysteria
4
4
5
+ by [ @spamegg1 ] ( https://github.com/spamegg1 )
6
+
5
7
## Puzzle description
6
8
7
9
https://adventofcode.com/2024/day/1
8
10
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
+
9
70
## Solutions from the community
10
71
11
72
- [ Solution] ( https://github.com/rmarbeck/advent2024/tree/main/day1 ) by [ Raphaël Marbeck] ( https://github.com/rmarbeck )
0 commit comments