43:a8365c989b1c
Anton Shestakov <engored@ya.ru>, Thu, 06 Mar 2014 19:38:46 +0900
Get win stats by nicknames, not pids.

next change 50:3f31a4eec418
previous change 41:f32e096c5433

src/rps_rules.erl

Permissions: -rw-r--r--

Other formats: Feeds:
-module(rps_rules).
-export([parse/1, winning_hand/2]).
-include("rps_rules.hrl").
add_unique(Elem, List) ->
case lists:member(Elem, List) of
true -> List;
false -> [Elem|List]
end.
parse(Text) ->
Tokens = lists:map(fun list_to_atom/1, string:tokens(Text, " ")),
parse(Tokens, #ruleinfo{}).
parse([V1,Label,V2|T], #ruleinfo{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
Acc = #ruleinfo{
hands=add_unique(V1, Hands),
beats=dict:append(V1, V2, Beats),
loses=dict:append(V2, V1, Loses),
why=dict:store({V1, V2}, Label, Why)},
parse([V2|T], Acc);
parse([_V2], Acc) ->
Acc.
% winner for 3 hands is:
% rock, rock, rock -> rock
% rock, paper, scissors -> undefined
% rock, paper, paper -> paper
% rock, rock, paper -> paper
winning_hand(Hands, State=#ruleinfo{}) ->
HSet = sets:from_list(Hands),
sets:fold(
fun(Hand, Acc) ->
Loses = dict:fetch(Hand, State#ruleinfo.loses),
case sets:is_disjoint(sets:from_list(Loses), HSet) of
false -> Acc;
true -> Hand
end
end, undefined, HSet).