Skip to content

Instantly share code, notes, and snippets.

@petemcfarlane
Last active July 18, 2017 09:45
Show Gist options
  • Save petemcfarlane/6602d64814a8bb2949e3f3d482c6fd5b to your computer and use it in GitHub Desktop.
Save petemcfarlane/6602d64814a8bb2949e3f3d482c6fd5b to your computer and use it in GitHub Desktop.
Rock Paper Scissors exercise from part 3 of https://www.futurelearn.com/courses/functional-programming-erlang
-module (rockpaperscissors).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
beat(rock) -> paper;
beat(paper) -> scissors;
beat(scissors) -> rock;
beat(_) -> error("expected rock, paper or scissors").
loose(rock) -> paper;
loose(paper) -> scissors;
loose(scissors) -> rock;
loose(_) -> error("expected rock, paper or scissors").
% I thought we could return a 1 or 2
% for player 1 or 2 respectively, and a 0 for draw
% but I decided it would be better to return the
% winning atom, e.g. `rock` (or `draw`) and let the players
% workout for themselves the winner.
% Then when I realised I needed to return a 1 for player one
% winning, -1 for player 2 winning and 0 for a draw, for use
% with `tournament/2` it became easier to just return that number
result(P1,P1) ->
0;
result(P1,P2) ->
case beat(P2) =:= P1 of
true -> 1;
false -> -1
end.
tournament(P1s, P2s) ->
Results = lists:zipwith(fun result/2, P1s, P2s),
lists:sum(Results).
result_test_() ->
[
?_assertEqual(1, result(rock,scissors)),
?_assertEqual(0, result(rock,rock)),
?_assertEqual(-1, result(rock,paper)),
?_assertEqual(-1, result(paper,scissors)),
?_assertEqual(1, result(paper,rock)),
?_assertEqual(0, result(paper,paper)),
?_assertEqual(-1, result(scissors,rock)),
?_assertEqual(1, result(scissors,paper)),
?_assertEqual(0, result(scissors,scissors))
].
tournament_test_() ->
[
?_assertEqual(0, tournament([rock], [rock])),
?_assertEqual(1, tournament([rock], [scissors])),
?_assertEqual(-1, tournament([rock], [paper])),
?_assertEqual(-1, tournament([rock,rock,paper,paper],[rock,paper,scissors,rock]))
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment