Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -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]).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement