36:4d40c4b8e8b0
Anton Shestakov <engored@ya.ru>, Mon, 03 Mar 2014 20:00:26 +0900
Move parse_rules and winning_hand to rps_rules.

next change 37:674e9537b6ab
previous change src/rps3.erl@35:1963573a943e

src/rps_rules.erl

Permissions: -rw-r--r--

Other formats: Feeds:
-module(rps_rules).
-export([parse/1, winning_hand/2]).
-record(state, {hands=[], beats=dict:new(), loses=dict:new(), why=dict:new()}).
parse(Text) ->
Tokens = lists:map(fun list_to_atom/1, string:tokens(Text, " ")),
parse(Tokens, #state{}).
parse([V1,Label,V2|T], #state{hands=Hands, beats=Beats, loses=Loses, why=Why}) ->
Acc = #state{
hands=[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=#state{}) ->
HSet = sets:from_list(Hands),
sets:fold(
fun(Hand, Acc) ->
Loses = dict:fetch(Hand, State#state.loses),
case sets:is_disjoint(sets:from_list(Loses), HSet) of
false -> Acc;
true -> Hand
end
end, undefined, HSet).