Skip to content

Instantly share code, notes, and snippets.

@paulmr
Created April 26, 2017 18:18
Show Gist options
  • Save paulmr/44f911a129b8a039a67c999ee1aaf835 to your computer and use it in GitHub Desktop.
Save paulmr/44f911a129b8a039a67c999ee1aaf835 to your computer and use it in GitHub Desktop.
Advent of Code 2015, Day 21
-module(advent21).
-export([main/0, main/1]).
winner(PD, PA, BD, BA, PHP, BHP) ->
Req = BHP / max(1, (PD - BA)),
Avail = PHP / max((BD - PA), 1),
Req =< Avail.
-define(Weapons, [ { 8, 4, 0 },
{ 10, 5, 0 },
{ 25, 6, 0 },
{ 40, 7, 0 },
{74, 8, 0 }
]).
-define(Armour, [ { 0, 0, 0 },
{ 13, 0, 1 },
{ 31, 0, 2 },
{ 53, 0, 3 },
{ 75, 0, 4 },
{102, 0, 5 }
]).
-define(Rings, [ { 0, 0, 0 },
{ 0, 0, 0 },
{ 25, 1, 0 },
{ 50, 2, 0 },
{ 100,3, 0 },
{ 20, 0, 1 },
{ 40, 0, 2 },
{ 80, 0, 3 }
]).
choices() ->
[ [ W, A, R1, R2 ] ||
W <- ?Weapons,
A <- ?Armour,
R1 <- ?Rings,
R2 <- ?Rings -- [R1]].
cost(Items) ->
lists:foldl(
fun ({Cost, _, _}, Acc) ->
Acc + Cost
end,
0, Items).
search1(PHP, BHP, BD, BA) ->
Wins = lists:filtermap(
fun (Items) ->
{ PD, PA } = player(Items),
case winner(PD, PA, BD, BA, PHP, BHP) of
true -> { true, cost(Items) };
false -> false
end
end, choices()),
hd(lists:sort(Wins)).
search2(PHP, BHP, BD, BA) ->
Wins = lists:filtermap(
fun (Items) ->
{ PD, PA } = player(Items),
case winner(PD, PA, BD, BA, PHP, BHP) of
false -> { true, cost(Items) };
true -> false
end
end, choices()),
lists:last(lists:sort(Wins)).
player(Items) -> player(Items, {0,0}).
player([], Acc) -> Acc;
player([H|T], { D, A }) ->
{ _Cost, ItemD, ItemA } = H,
player(T, { D + ItemD, A + ItemA }).
main() -> main([]).
main([]) -> search(100, 8, 2);
main(Args) ->
apply(
fun search/3,
[ list_to_integer(A) || A <- Args ]).
search(BHP, BD, BA) ->
Part1 = search1(100, BHP, BD, BA),
Part2 = search2(100, BHP, BD, BA),
io:format("Part 1: ~B~n", [Part1]),
io:format("Part 2: ~B~n", [Part2]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment