40:7d4b76367349
Anton Shestakov <engored@ya.ru>, Mon, 03 Mar 2014 22:17:13 +0900
Keeping comments up-to-date with code.

next change 42:82a465d8a5c1
previous change 34:19dac34d9a51

src/rps5.erl

Permissions: -rw-r--r--

Other formats: Feeds:
-module(rps5).
-export([
get_hands/0,
beats/1, test_beats/0,
loses/1, test_loses/0,
winning_hand/1, test_winning_hand/0]).
get_hands() -> [rock, paper, scissors, spock, lizard].
beats(rock) ->
[scissors, lizard];
beats(paper) ->
[spock, rock];
beats(scissors) ->
[lizard, paper];
beats(spock) ->
[rock, scissors];
beats(lizard) ->
[paper, spock].
loses(lizard) ->
[scissors, rock];
loses(spock) ->
[paper, lizard];
loses(scissors) ->
[rock, spock];
loses(paper) ->
[lizard, scissors];
loses(rock) ->
[spock, paper].
test_beats() ->
lists:foreach(
fun(H) ->
io:format("~w beats ~w.~n", [H, beats(H)])
end,
get_hands()).
test_loses() ->
lists:foreach(
fun(H) ->
io:format("~w loses to ~w.~n", [H, loses(H)])
end,
get_hands()).
% 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) ->
Loses = loses(Hand),
case sets:is_disjoint(sets:from_list(Loses), HSet) of
true -> Hand;
false -> Acc
end
end, undefined, HSet).
test_winning_hand() ->
Exclude = fun(Hand) -> lists:delete(Hand, get_hands()) end,
Cases = [
[rock, rock, rock],
[rock, paper, scissors],
[rock, paper, paper],
[rock, rock, paper]
|lists:map(Exclude, get_hands())
],
lists:foreach(
fun(Hands) ->
Winner = winning_hand(Hands),
io:format("~w wins in ~w.~n", [Winner, Hands])
end,
Cases).