Skip to content

Commit

Permalink
moar pokers
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Alexandrowicz committed Nov 15, 2012
1 parent eb70bac commit cc76a42
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 9 deletions.
36 changes: 33 additions & 3 deletions poker_hands.erl
@@ -1,7 +1,37 @@
-module(poker_hands).
-export([sum/1, rank/1]).
-export([card/1, rank/1, hand/1, highcard/1, flush/1, straight/1, straight_flush/1]).

sum([X|R]) -> X + sum(R);
sum([]) -> 0.

string_to_suit($H) -> h;
string_to_suit($D) -> d;
string_to_suit($C) -> c;
string_to_suit($S) -> s.

string_to_rank(N) ->
string:str("123456789TJQKA",[N]).

card([X,Y]) -> {string_to_rank(X),string_to_suit(Y)}.

rank({X,_}) -> X.

hand([X,Y]) -> [card([X,Y])];
hand([X,Y,32|R]) ->
[card([X,Y])] ++ hand(R).

% [{2, h}, {3, s}, {4, s}, {5, s}]
highcard(L) ->
lists:max(lists:map(fun rank/1, L)).

flush([{_,S},{_,S},{_,S},{_,S},{_,S}]) -> true;
flush(_) -> false.

straight_sorted([{R1,_}, {R2,_}]) -> R2 - R1 =:= 1;
straight_sorted([{R1,_}, {R2,_} = C|Xs]) when R2 - R1 =:= 1 ->
straight_sorted([C|Xs]);
straight_sorted(_) -> false.

straight(L) ->
straight_sorted(lists:sort(L)).

straight_flush(L) ->
true.
31 changes: 25 additions & 6 deletions poker_hands_tests.erl
@@ -1,11 +1,30 @@
-module(poker_hands_tests).
-include_lib("eunit/include/eunit.hrl").
-import(poker_hands, [card/1, rank/1, hand/1, highcard/1, flush/1, straight/1, straight_flush/1]).

% sum_test() ->
% ?assertEqual(0, poker_hands:sum([])),
% ?assertEqual(0, poker_hands:sum([0])),
% ?assertEqual(6, poker_hands:sum([1,2,3,4,-4])).
card_test() ->
?assertEqual({3, h}, card("3H")),
?assertEqual({2, h}, card("2H")),
?assertEqual({13, h}, card("KH")).

rank_test() ->
?assertEqual(2, poker_hands:rank({2, h})),
?assertEqual(3, poker_hands:rank({3, h})).
?assertEqual(2, rank({2, h})),
?assertEqual(3, rank({3, h})).

hand_test() ->
?assertEqual([{3, h}, {2, s}, {13, h}], hand("3H 2S KH")).

highcard_test() ->
?assertEqual(10, highcard(hand("2H 3S 4D 5C TH"))),
?assertEqual(13, highcard(hand("2H 3S 4D KH 5C"))).

flush_test() ->
?assertEqual(true, flush(hand("2H 3H 6H 8H JH"))),
?assertEqual(false, flush(hand("2H 3C 6H 8H AC"))).

straight_test() ->
?assertEqual(true, straight(hand("2H 3H 4H 5H 6H"))),
?assertEqual(false, straight(hand("2H 3H 8H 5H 6H"))).

straight_flush_test() ->
?assertEqual(true, straight_flush(hand("2H 3H 4H 5H 6H"))).

0 comments on commit cc76a42

Please sign in to comment.