From cc76a42320871e34a52c84e0509273f21232b5c4 Mon Sep 17 00:00:00 2001 From: Tom Alexandrowicz Date: Wed, 14 Nov 2012 19:28:04 -0500 Subject: [PATCH] moar pokers --- poker_hands.erl | 36 +++++++++++++++++++++++++++++++++--- poker_hands_tests.erl | 31 +++++++++++++++++++++++++------ 2 files changed, 58 insertions(+), 9 deletions(-) diff --git a/poker_hands.erl b/poker_hands.erl index de24f26..df5931d 100644 --- a/poker_hands.erl +++ b/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. diff --git a/poker_hands_tests.erl b/poker_hands_tests.erl index 9261045..ab554df 100644 --- a/poker_hands_tests.erl +++ b/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})). \ No newline at end of file + ?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"))). \ No newline at end of file