1
0
Fork 0

day24 solution

main
Andrew Coleman 2017-12-24 02:02:16 -05:00
parent 9fe074b396
commit 0c219c6f2f
4 changed files with 152 additions and 0 deletions

8
day24/Makefile Normal file
View File

@ -0,0 +1,8 @@
all: day24.beam
erl -noshell -s day24 start -s init stop
day24.beam:
erlc day24.erl
clean:
rm -f day24.beam

79
day24/day24.erl Normal file
View File

@ -0,0 +1,79 @@
-module(day24).
-export([start/0]).
read_input(Filename)
-> { ok, Input } = file:read_file(Filename),
lists:map(fun(X) ->
[A,B|_] = re:split(X, "/"),
{ AInt, _ } = string:to_integer(A),
{ BInt, _ } = string:to_integer(B),
{ AInt, BInt }
end, re:split(string:chomp(Input), "\n")).
strongest_bridge(Input)
-> strongest_bridge(Input, 0, 0, []).
strongest_bridge([], _LastEdge, Sum, Train)
-> { Sum, Train };
strongest_bridge(Input, LastEdge, Sum, Train)
-> { Matching, _ } = lists:partition(fun(X) ->
{ A, B } = X,
(A == LastEdge) or (B == LastEdge)
end, Input),
if length(Matching) == 0 -> { Sum, Train };
true ->
MatchingSums = lists:map(fun(X) ->
{ _, Remaining } = lists:partition(fun(Y) -> Y == X end, Input),
{ A, B } = X,
NewTrain = lists:append(Train, [X]),
NewSum = Sum + A + B,
if A == LastEdge -> strongest_bridge(Remaining, B, NewSum, NewTrain);
true -> strongest_bridge(Remaining, A, NewSum, NewTrain)
end
end, Matching),
[FirstSum|_] = lists:sort(fun(X, Y) ->
{ A, _ } = X,
{ B, _ } = Y,
B =< A
end, MatchingSums),
FirstSum
end.
longest_bridge(Input)
-> longest_bridge(Input, 0, 0, []).
longest_bridge([], _LastEdge, Sum, Train)
-> { Sum, Train };
longest_bridge(Input, LastEdge, Sum, Train)
-> { Matching, _ } = lists:partition(fun(X) ->
{ A, B } = X,
(A == LastEdge) or (B == LastEdge)
end, Input),
if length(Matching) == 0 -> { Sum, Train };
true ->
MatchingSums = lists:map(fun(X) ->
{ _, Remaining } = lists:partition(fun(Y) -> Y == X end, Input),
{ A, B } = X,
NewTrain = lists:append(Train, [X]),
NewSum = Sum + A + B,
if A == LastEdge -> longest_bridge(Remaining, B, NewSum, NewTrain);
true -> longest_bridge(Remaining, A, NewSum, NewTrain)
end
end, Matching),
[FirstSum|_] = lists:sort(fun(X, Y) ->
{ A, I } = X,
{ B, J } = Y,
if length(I) == length(J) -> B =< A;
true -> length(J) =< length(I)
end
end, MatchingSums),
FirstSum
end.
start()
-> SampleInput = read_input("sample"),
io:fwrite("~p~n", [strongest_bridge(SampleInput)]),
io:fwrite("~p~n", [longest_bridge(SampleInput)]),
ProblemInput = read_input("problem"),
io:fwrite("~p~n", [strongest_bridge(ProblemInput)]),
io:fwrite("~p~n", [longest_bridge(ProblemInput)]).

57
day24/problem Normal file
View File

@ -0,0 +1,57 @@
14/42
2/3
6/44
4/10
23/49
35/39
46/46
5/29
13/20
33/9
24/50
0/30
9/10
41/44
35/50
44/50
5/11
21/24
7/39
46/31
38/38
22/26
8/9
16/4
23/39
26/5
40/40
29/29
5/20
3/32
42/11
16/14
27/49
36/20
18/39
49/41
16/6
24/46
44/48
36/4
6/6
13/6
42/12
29/41
39/39
9/3
30/2
25/20
15/6
15/23
28/40
8/7
26/23
48/10
28/28
2/13
48/14

8
day24/sample Normal file
View File

@ -0,0 +1,8 @@
0/2
2/2
2/3
3/4
3/5
0/1
10/1
9/10