Last active
December 9, 2024 06:57
-
-
Save joeytrapp/bb281fada977ec9b74803bb7ba5eff6d to your computer and use it in GitHub Desktop.
Advent of Code 2024 Day 1 Part 1 and Part 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(aoc). | |
-export([main/1]). | |
-import(file, [read_file/1]). | |
-import(lists, [unzip/1, map/2, zip/2, sort/1, foldl/3, filter/2, sum/1]). | |
-import(maps, [get/3, update_with/4]). | |
-import(string, [is_empty/1, split/3, trim/1]). | |
main([Path]) -> | |
{ok, String} = read_file(Path), | |
{A, B} = unzip(map(fun line_elements/1, split(String, "\n", all))), | |
io:format("Sum: ~p~n", [sum_diffs(zip(sort(A), sort(B)))]), | |
io:format("SimScore: ~p~n", [compute_sim_score(make_counts_map(B), A)]), | |
erlang:halt(0). | |
line_elements(Line) when is_binary(Line) -> | |
list_to_tuple(filter(fun(S) -> not is_empty(S) end, split(trim(Line), " ", all))). | |
sum_diffs(L) when is_list(L) -> | |
sum(map(fun({A, B}) -> abs(binary_to_integer(A) - binary_to_integer(B)) end, L)). | |
make_counts_map(L) when is_list(L) -> | |
foldl(fun(K, M) -> update_with(K, fun(V) -> V + 1 end, 1, M) end, #{}, L). | |
compute_sim_score(M, L) when is_map(M) and is_list(L) -> | |
foldl(fun(X, S) -> S + get(X, M, 0) * binary_to_integer(X) end, 0, L). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment