Skip to content

Commit 71bbf52

Browse files
committed
day1 part2
1 parent 52bed0e commit 71bbf52

File tree

2 files changed

+67
-3
lines changed

2 files changed

+67
-3
lines changed

resources/2024/day01-requirement.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,35 @@ Example calculation:
2222
- Total distance: 2+1+0+1+2+5 = 11
2323

2424
The puzzle asks you to perform this calculation on the actual input lists to determine the total distance.
25+
26+
--- Part Two ---
27+
28+
The puzzle now focuses on calculating a "similarity score" between two lists of numbers. The process is as follows:
29+
30+
For each number in the left list:
31+
32+
- Count how many times that number appears in the right list
33+
- Multiply the number by its frequency in the right list
34+
- Add this product to a running total (similarity score)
35+
36+
Key points:
37+
38+
- Numbers that don't appear in the right list contribute 0 to the score
39+
- The score is calculated by multiplying each left list number by its frequency in the right list
40+
- The goal is to find the total similarity score
41+
42+
Example calculation:
43+
44+
- Left list: [3, 4, 2, 1, 3, 3]
45+
- Right list: [4, 3, 5, 3, 9, 3]
46+
- Breakdown:
47+
- 3 appears 3 times in right list: 3 * 3 = 9
48+
- 4 appears 1 time in right list: 4 * 1 = 4
49+
- 2 appears 0 times in right list: 2 * 0 = 0
50+
- 1 appears 0 times in right list: 1 * 0 = 0
51+
- 3 appears 3 times in right list: 3 * 3 = 9
52+
- 3 appears 3 times in right list: 3 * 3 = 9
53+
54+
- Total similarity score: 9 + 4 + 0 + 0 + 9 + 9 = 31
55+
56+
The puzzle asks you to calculate this similarity score for the actual input lists.

src/adventofcode2024/day01.odin

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,44 @@ main :: proc() {
2121
append(&y, strconv.atoi(s[1]))
2222
}
2323

24-
slice.sort(x[:])
25-
slice.sort(y[:])
24+
part1_result := part1(x[:], y[:])
25+
fmt.println(part1_result) // 1765812
26+
27+
part2_result := part2(x[:], y[:])
28+
fmt.println(part2_result) // 20520794
29+
}
30+
31+
part1 :: proc(x, y: []int) -> int {
32+
slice.sort(x)
33+
slice.sort(y)
2634

2735
result := 0
2836
for i in 0 ..< len(x) {
2937
result += abs(x[i] - y[i])
3038
}
31-
fmt.println(result) // 1765812
39+
40+
return result
41+
}
42+
43+
part2 :: proc(x, y: []int) -> int {
44+
m: map[int]int
45+
defer delete(m)
46+
47+
result := 0
48+
for i in x {
49+
if freq, ok := m[i]; ok {
50+
result += i * freq
51+
} else {
52+
freq := 0
53+
for j in y {
54+
if i == j {
55+
freq += 1
56+
}
57+
}
58+
result += i * freq
59+
m[i] = freq
60+
}
61+
}
62+
63+
return result
3264
}

0 commit comments

Comments
 (0)