# Advent of Code 2022 Day 3 - Discussions

This topic is about Day 3 of the Advent of Code 2022 .

Sorry for the delay in opening this post. Hope we already have some solutions to `day 3`

The entry code is:
`370884-a6a71927`

Good luck!

4 Likes

Todays challenge went much smoother for me than yesterday’s:

``````main(File) ->
Data = [ binary_to_list(N) || N <- binary:split(RawData, <<"\n">>, [global, trim]) ],
io:format("part 1: ~p~n", [solve1(Data)]),
io:format("part 2: ~p~n", [solve2(Data)]).

solve1(Data) ->
lists:sum([ begin
{Left, Right} = lists:split(length(D) div 2, D),
intersection_priority([Left, Right])
end
|| D <- Data ]).

intersection_priority(Lists) ->
[Item] = ordsets:intersection([ ordsets:from_list(L) || L <- Lists ]),
priority(Item).

priority(X) when X >= \$A, X =< \$Z -> X - \$A + 27;
priority(X) when X >= \$a, X =< \$z -> X - \$a + 1.

solve2([X, Y, Z|Rest]) ->
intersection_priority([X, Y, Z]) + solve2(Rest);
solve2([]) ->
0.
``````
2 Likes

`ordsets:intersection` - I knew there must be an OTP way of doing this, but I had completely forgotten `ordsets`.

1 Like

I think I am finally getting the hang of it. Here’s Day 3:

``````-module(day_3).

-export([solve/0, chunks/2]).

input() ->
RawRucksacks.

solve() ->
RawRucksacks = parse(input()),
Solve1 = solve1(RawRucksacks),
Solve2 = solve2(RawRucksacks),
{Solve1, Solve2}.

solve1(RawRucksacks) ->
total_priority(lists:map(fun(X) -> compartment(X) end, RawRucksacks)).

solve2(RawRucksacks) ->
total_priority([common(X) || X <- chunks(RawRucksacks, 3)]).

parse(RawRucksacks) ->
[binary:bin_to_list(Subject)
|| Subject <- binary:split(RawRucksacks, <<"\n">>, [global, trim])].

compartment(A) ->
{First, Last} = lists:split(length(A) div 2, A),
ordsets:intersection(
ordsets:from_list(First), ordsets:from_list(Last)).

priority(X) when X =< 90 ->
X - hd("A") + 27;
priority(X) when X >= 97 ->
X - hd("a") + 1.

chunks([], _) ->
[];
chunks(List, Len) when Len > length(List) ->
[List];
chunks(List, Len) ->

common([A, B, C]) ->
ordsets:intersection(
ordsets:from_list(A),
ordsets:intersection(
ordsets:from_list(B), ordsets:from_list(C))).

total_priority(CommonItems) ->
lists:sum([priority(hd(X)) || X <- CommonItems]).
``````
2 Likes

til `begin` and `end`. I should keep a journal of my Erlearnings 2 Likes