feat: Add similarity score calculation for Day 1 Part 2

This commit is contained in:
Ruidy (aider) 2024-12-01 10:12:03 +01:00
parent 5ff0e5588c
commit fee5ec25f3
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
2 changed files with 42 additions and 0 deletions

View file

@ -53,4 +53,25 @@ defmodule AdventCode2024 do
|> Enum.map(fn {a, b} -> abs(a - b) end)
|> Enum.sum()
end
@doc """
Calculates the similarity score between two lists.
For each number in the left list, multiplies it by the number of times it appears in the right list.
Returns the sum of all these products.
## Examples
iex> AdventCode2024.calculate_similarity_score([3, 4, 2, 1, 3, 3], [4, 3, 5, 3, 9, 3])
31
"""
def calculate_similarity_score(left_list, right_list) do
frequencies = Enum.frequencies(right_list)
left_list
|> Enum.map(fn num ->
num * Map.get(frequencies, num, 0)
end)
|> Enum.sum()
end
end

View file

@ -31,4 +31,25 @@ defmodule AdventCode2024Test do
assert AdventCode2024.calculate_total_distance([1], [3]) == 2
end
end
describe "Day 1 Part 2: Similarity Score" do
test "calculates similarity score using example input" do
left_list = [3, 4, 2, 1, 3, 3]
right_list = [4, 3, 5, 3, 9, 3]
assert AdventCode2024.calculate_similarity_score(left_list, right_list) == 31
end
test "handles empty lists for similarity score" do
assert AdventCode2024.calculate_similarity_score([], []) == 0
end
test "handles lists with no matches" do
assert AdventCode2024.calculate_similarity_score([1, 2], [3, 4]) == 0
end
test "handles lists with all matches" do
assert AdventCode2024.calculate_similarity_score([1, 1], [1, 1]) == 4
end
end
end