mirror of
https://github.com/rjNemo/ai_advent_code_2024
synced 2026-06-11 21:16:39 +00:00
feat: Add similarity score calculation for Day 1 Part 2
This commit is contained in:
parent
5ff0e5588c
commit
fee5ec25f3
2 changed files with 42 additions and 0 deletions
|
|
@ -53,4 +53,25 @@ defmodule AdventCode2024 do
|
||||||
|> Enum.map(fn {a, b} -> abs(a - b) end)
|
|> Enum.map(fn {a, b} -> abs(a - b) end)
|
||||||
|> Enum.sum()
|
|> Enum.sum()
|
||||||
end
|
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
|
end
|
||||||
|
|
|
||||||
|
|
@ -31,4 +31,25 @@ defmodule AdventCode2024Test do
|
||||||
assert AdventCode2024.calculate_total_distance([1], [3]) == 2
|
assert AdventCode2024.calculate_total_distance([1], [3]) == 2
|
||||||
end
|
end
|
||||||
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
|
end
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue