13:30f6287441d2
Anton Shestakov <engored@ya.ru>, Wed, 26 Feb 2014 15:06:12 +0900
Separate winner/1 and winning_hand/1, as their logic is different.

next change 15:36f639142522
previous change 12:23a27ec9f362

rps3.erl

Permissions: -rw-r--r--

Other formats: Feeds:
-module(rps3).
-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) ->
beats(H, get_rules()).
beats(H, [H|Tail]) ->
lists:last(Tail);
beats(H, [B,H|_]) ->
B;
beats(H, [_|T]) ->
beats(H, T).
loses(H) ->
beats(H, lists:reverse(get_rules())).
test_beats() ->
lists:foreach(
fun(H) ->
io:format("~w beats ~w.~n", [H, beats(H)])
end,
get_rules()).
test_loses() ->
lists:foreach(
fun(H) ->
io:format("~w loses to ~w.~n", [H, loses(H)])
end,
get_rules()).
% winner for 3 hands is:
% rock, rock, rock -> rock
% rock, paper, scissors -> undefined
% rock, paper, paper -> paper
% rock, rock, paper -> paper
winning_hand(Hands) ->
HSet = sets:from_list(Hands),
sets:fold(
fun(Hand, Acc) ->
case sets:is_element(loses(Hand), HSet) of
true -> Acc;
false -> Hand
end
end, undefined, HSet).
test_winning_hand() ->
Cases = [
[rock, rock, rock],
[rock, paper, scissors],
[rock, paper, paper],
[rock, rock, paper],
[rock, paper],
[paper, scissors],
[scissors, rock]
],
lists:foreach(
fun(Hands) ->
Winner = winning_hand(Hands),
io:format("~w wins in ~w.~n", [Winner, Hands])
end,
Cases).