--- a/rps.erl Wed Feb 26 02:28:07 2014 +0900
+++ b/rps.erl Wed Feb 26 15:06:12 2014 +0900
--import(rps3, [get_rules/0, beats/1]).
+-import(rps3, [get_rules/0, winning_hand/1]).
% rock, rock, paper -> {paper, Who}
winner(Choices) when length(Choices) > 1 ->
- HSet = sets:from_list([Hand || {Hand, _} <- Choices]),
- RSet = sets:from_list(get_rules()),
- Absents = sets:subtract(RSet, HSet),
- case sets:size(Absents) of
- Absent = hd(sets:to_list(Absents)),
- Unbeaten = beats(Absent),
- Winners = [{Hand, Who} || {Hand, Who} <- Choices, Hand =:= Unbeaten],
- case length(Winners) of
+ PlayersByHand = lists:foldl(
+ fun({Hand, Who}, Acc) ->
+ dict:append(Hand, Who, Acc)
+ end, dict:new(), Choices),
+ WHand = winning_hand([Hand || {Hand, _} <- Choices]),
+ WHand =:= undefined -> [];
+ WHand =/= undefined -> dict:fetch(WHand, PlayersByHand)
+ case length(Players) of
+ 1 -> {WHand, hd(Players)};
--- a/rps3.erl Wed Feb 26 02:28:07 2014 +0900
+++ b/rps3.erl Wed Feb 26 15:06:12 2014 +0900
--export([get_rules/0, beats/1, test_beats/0]).
+-export([get_rules/0, beats/1, test_beats/0, test_loses/0, winning_hand/1, test_winning_hand/0]).
get_rules() -> [rock, paper, scissors].
+ beats(H, lists:reverse(get_rules())).
- io:format("~w beats ~w.~n", [C, beats(C)])
+ io:format("~w beats ~w.~n", [H, beats(H)])
+ io:format("~w loses to ~w.~n", [H, loses(H)])
+% winner for 3 hands is:
+% rock, rock, rock -> rock
+% rock, paper, scissors -> undefined
+% rock, paper, paper -> paper
+% rock, rock, paper -> paper
+ HSet = sets:from_list(Hands),
+ case sets:is_element(loses(Hand), HSet) of
+ [rock, paper, scissors],
+ Winner = winning_hand(Hands),
+ io:format("~w wins in ~w.~n", [Winner, Hands])