Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. -module(advent21).
  2. -export([main/0, main/1]).
  3.  
  4. winner(PD, PA, BD, BA, PHP, BHP) ->
  5. Req = BHP / max(1, (PD - BA)),
  6. Avail = PHP / max((BD - PA), 1),
  7. Req =< Avail.
  8.  
  9. -define(Weapons, [ { 8, 4, 0 },
  10. { 10, 5, 0 },
  11. { 25, 6, 0 },
  12. { 40, 7, 0 },
  13. {74, 8, 0 }
  14. ]).
  15. -define(Armour, [ { 0, 0, 0 },
  16. { 13, 0, 1 },
  17. { 31, 0, 2 },
  18. { 53, 0, 3 },
  19. { 75, 0, 4 },
  20. {102, 0, 5 }
  21. ]).
  22. -define(Rings, [ { 0, 0, 0 },
  23. { 0, 0, 0 },
  24. { 25, 1, 0 },
  25. { 50, 2, 0 },
  26. { 100,3, 0 },
  27. { 20, 0, 1 },
  28. { 40, 0, 2 },
  29. { 80, 0, 3 }
  30. ]).
  31.  
  32. choices() ->
  33. [ [ W, A, R1, R2 ] ||
  34. W <- ?Weapons,
  35. A <- ?Armour,
  36. R1 <- ?Rings,
  37. R2 <- ?Rings -- [R1]].
  38.  
  39. cost(Items) ->
  40. lists:foldl(
  41. fun ({Cost, _, _}, Acc) ->
  42. Acc + Cost
  43. end,
  44. 0, Items).
  45.  
  46. search1(PHP, BHP, BD, BA) ->
  47. Wins = lists:filtermap(
  48. fun (Items) ->
  49. { PD, PA } = player(Items),
  50. case winner(PD, PA, BD, BA, PHP, BHP) of
  51. true -> { true, cost(Items) };
  52. false -> false
  53. end
  54. end, choices()),
  55. hd(lists:sort(Wins)).
  56.  
  57. search2(PHP, BHP, BD, BA) ->
  58. Wins = lists:filtermap(
  59. fun (Items) ->
  60. { PD, PA } = player(Items),
  61. case winner(PD, PA, BD, BA, PHP, BHP) of
  62. false -> { true, cost(Items) };
  63. true -> false
  64. end
  65. end, choices()),
  66. lists:last(lists:sort(Wins)).
  67.  
  68. player(Items) -> player(Items, {0,0}).
  69. player([], Acc) -> Acc;
  70. player([H|T], { D, A }) ->
  71. { _Cost, ItemD, ItemA } = H,
  72. player(T, { D + ItemD, A + ItemA }).
  73.  
  74. main() -> main([]).
  75. main([]) -> search(100, 8, 2);
  76. main(Args) ->
  77. apply(
  78. fun search/3,
  79. [ list_to_integer(A) || A <- Args ]).
  80.  
  81. search(BHP, BD, BA) ->
  82. Part1 = search1(100, BHP, BD, BA),
  83. Part2 = search2(100, BHP, BD, BA),
  84. io:format("Part 1: ~B~n", [Part1]),
  85. io:format("Part 2: ~B~n", [Part2]).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement