Add 2024/day1/part2.erl
This commit is contained in:
parent
80a0b71a15
commit
9c043098be
|
@ -0,0 +1,30 @@
|
|||
-module(day1_part2).
|
||||
-export([main/0]).
|
||||
|
||||
% Main entry point
|
||||
main() ->
|
||||
{ok, Content} = file:read_file("input.txt"),
|
||||
Lines = string:split(string:trim(Content), "\n", all),
|
||||
{List1, List2} = lists:foldl(fun parse_line/2, {[], []}, Lines),
|
||||
CountMap = build_count_map(List2),
|
||||
SimilarityScore = calculate_similarity_score(List1, CountMap),
|
||||
io:format("Result: ~p~n", [SimilarityScore]).
|
||||
|
||||
% Parse a single line into two integers and accumulate them into lists
|
||||
parse_line(Line, {Acc1, Acc2}) ->
|
||||
[Str1, Str2] = string:split(string:trim(Line), " ", all),
|
||||
{Num1, _} = string:to_integer(Str1),
|
||||
{Num2, _} = string:to_integer(Str2),
|
||||
{[Num1 | Acc1], [Num2 | Acc2]}.
|
||||
|
||||
% Build a map of counts for elements in List2
|
||||
build_count_map(List) ->
|
||||
lists:foldl(fun(Elem, Acc) ->
|
||||
maps:update_with(Elem, fun(Count) -> Count + 1 end, 1, Acc)
|
||||
end, #{}, List).
|
||||
|
||||
% Calculate the total similarity score
|
||||
calculate_similarity_score(List1, CountMap) ->
|
||||
lists:foldl(fun(Elem, Acc) ->
|
||||
Acc + Elem * maps:get(Elem, CountMap, 0)
|
||||
end, 0, List1).
|
Loading…
Reference in New Issue