# Advent of Code Day 4 - Discussions

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

`day 4` - begins in less than two hours and let’s hope we get some great submissions.

I must admit, I had quite a few aha moments seeing yesterdays code. I also spent some time today looking into previous Erlang solutions for Advent of Code and appreciated the richness of Erlang modules. I surely will spend more time behind Erlang now and feel it would add to my Elixir know how (more than I previously thought it would).

The entry code is:
`370884-a6a71927`

Good luck!

2 Likes

Thank you for creating threads @mafinar

I assume this challenge is bit easier with elixir ranges, my solution:

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

solve1(Data) ->
length([ true || [N1, N2, N3, N4] <- Data, contained(N1, N2, N3, N4) ]).

solve2(Data) ->
length([ true || [N1, N2, N3, N4] <- Data, overlap(N1, N2, N3, N4) ]).

contained(N1, N2, N3, N4) ->
(N1 >= N3 andalso N2 =< N4)
orelse (N3 >= N1 andalso N4 =< N2).

overlap(N1, N2, N3, N4) ->
not (N1 > N4 orelse N3 > N2).
``````
2 Likes

`:binary` is a treasure trove! I got to learn that this AoC.

1 Like

I think I am getting the hang of Erlang. Although, I am not sure if my code is idiomatic. Also, I’m glad they just don’t look Elixir written in Erlang (not that it’d be a bad thing I guess?).

I still ain’t getting the hang of list comprehension. I do find a bit weird the data structure and function ordering on higher order functions. Like, `lists:map` has the function as first parameter but `binary:split` has the binary as the first parameter.

``````-module(day_4).

-export([solve/0]).

input() ->
RawAssignments.

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

solve1(Assignments) ->
length(lists:filter(fun is_containing/1, Assignments)).

solve2(Assignments) ->
length(lists:filter(fun is_overlapping/1, Assignments)).

parse(RawAssignments) ->
[parse_ranges(Assignment)
|| Assignment
<- [binary:split(RawAssignment, <<",">>, [global, trim])
|| RawAssignment <- binary:split(RawAssignments, <<"\n">>, [global, trim])]].

is_containing({{X1, Y1}, {X2, Y2}}) when X1 =< X2, Y1 >= Y2; X2 =< X1, Y2 >= Y1 ->
true;
is_containing(_) ->
false.

is_overlapping({{X1, Y1}, {X2, Y2}}) when X1 =< X2, Y1 >= X2; X2 =< X1, Y2 >= X1 ->
true;
is_overlapping(_) ->
false.

parse_ranges([Range1, Range2]) ->
[From1, To1] = binary:split(Range1, <<"-">>),
[From2, To2] = binary:split(Range2, <<"-">>),
{{to_int(From1), to_int(To1)}, {to_int(From2), to_int(To2)}}.

to_int(Value) ->
list_to_integer(binary_to_list(Value)).
``````
2 Likes