ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# bkhl's solution

## to Poker in the Rust Track

Published at Apr 10 2019 · 0 comments
Instructions
Test suite
Solution

Pick the best hand(s) from a list of poker hands.

See wikipedia for an overview of poker hands.

## Hints

• Ranking a list of poker hands can be considered a sorting problem.
• Rust provides the sort method for `Vec<T> where T: Ord`.
• `Ord` types form a total order: exactly one of `a < b`, `a == b`, or `a > b` must be true.
• Poker hands do not conform to a total order: it is possible for two hands to be non-equal but have equal sort order. Example: `"3S 4S 5D 6H JH"`, `"3H 4H 5C 6C JD"`.
• Rust provides the `PartialOrd` trait to handle the case of sortable things which do not have a total order. However, it doesn't provide a standard `sort` method for `Vec<T> where T: PartialOrd`. The standard idiom to sort a vector in this case is `your_vec.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::{Less|Equal|Greater}));`, depending on your needs.
• You might consider implementing a type representing a poker hand which implements `PartialOrd`.

## Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

## Writing the Code

Execute the tests with:

``````\$ cargo test
``````

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the `tests` directory and remove the `#[ignore]` flag from the next test and get the tests to pass again. Each separate test is a function with `#[test]` flag above it. Continue, until you pass every test.

If you wish to run all ignored tests without editing the tests source file, use:

``````\$ cargo test -- --ignored
``````

To run a specific test, for example `some_test`, you can use:

``````\$ cargo test some_test
``````

If the specific test is ignored use:

``````\$ cargo test some_test -- --ignored
``````

## Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

``````cargo fmt
``````

To see, if your solution contains some common ineffective use cases, inside the solution directory use

``````cargo clippy --all-targets
``````

## Submitting the solution

Generally you should submit all files in which you implemented your solution (`src/lib.rs` in most cases). If you are using any external crates, please consider submitting the `Cargo.toml` file. This will make the review process faster and clearer.

## Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

## Source

Inspired by the training course from Udacity. https://www.udacity.com/course/viewer#!/c-cs212/

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### poker.rs

``````use poker::winning_hands;
use std::collections::HashSet;

fn hs_from<'a>(input: &[&'a str]) -> HashSet<&'a str> {
let mut hs = HashSet::new();
for item in input.iter() {
hs.insert(*item);
}
hs
}

/// Test that the expected output is produced from the given input
/// using the `winning_hands` function.
///
/// Note that the output can be in any order. Here, we use a HashSet to
/// abstract away the order of outputs.
fn test<'a, 'b>(input: &[&'a str], expected: &[&'b str]) {
assert_eq!(
hs_from(&winning_hands(input).expect("This test should produce Some value",)),
hs_from(expected)
)
}

#[test]
fn test_single_hand_always_wins() {
test(&["4S 5S 7H 8D JC"], &["4S 5S 7H 8D JC"])
}

#[test]
#[ignore]
fn test_highest_card_of_all_hands_wins() {
test(
&["4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH"],
&["3S 4S 5D 6H JH"],
)
}

#[test]
#[ignore]
fn test_a_tie_has_multiple_winners() {
test(
&[
"4D 5S 6S 8D 3C",
"2S 4C 7S 9H 10H",
"3S 4S 5D 6H JH",
"3H 4H 5C 6C JD",
],
&["3S 4S 5D 6H JH", "3H 4H 5C 6C JD"],
)
}

#[test]
#[ignore]
fn test_high_card_can_be_low_card_in_an_otherwise_tie() {
// multiple hands with the same high cards, tie compares next highest ranked,
// down to last card
test(&["3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S"], &["3S 5H 6S 8D 7H"])
}

#[test]
#[ignore]
fn test_one_pair_beats_high_card() {
test(&["4S 5H 6C 8D KH", "2S 4H 6S 4D JH"], &["2S 4H 6S 4D JH"])
}

#[test]
#[ignore]
fn test_highest_pair_wins() {
test(&["4S 2H 6S 2D JH", "2S 4H 6C 4D JD"], &["2S 4H 6C 4D JD"])
}

#[test]
#[ignore]
fn test_two_pairs_beats_one_pair() {
test(&["2S 8H 6S 8D JH", "4S 5H 4C 8C 5C"], &["4S 5H 4C 8C 5C"])
}

#[test]
#[ignore]
fn test_two_pair_ranks() {
// both hands have two pairs, highest ranked pair wins
test(&["2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D"], &["2S 8H 2D 8D 3H"])
}

#[test]
#[ignore]
// both hands have two pairs, with the same highest ranked pair,
// tie goes to low pair
test(&["2S QS 2C QD JH", "JD QH JS 8D QC"], &["JD QH JS 8D QC"])
}

#[test]
#[ignore]
// both hands have two identically ranked pairs,
// tie goes to remaining card (kicker)
test(&["JD QH JS 8D QC", "JS QS JC 2D QD"], &["JD QH JS 8D QC"])
}

#[test]
#[ignore]
fn test_three_of_a_kind_beats_two_pair() {
test(&["2S 8H 2H 8D JH", "4S 5H 4C 8S 4H"], &["4S 5H 4C 8S 4H"])
}

#[test]
#[ignore]
fn test_three_of_a_kind_ranks() {
//both hands have three of a kind, tie goes to highest ranked triplet
test(&["2S 2H 2C 8D JH", "4S AH AS 8C AD"], &["4S AH AS 8C AD"])
}

#[test]
#[ignore]
// with multiple decks, two players can have same three of a kind,
// ties go to highest remaining cards
}

#[test]
#[ignore]
fn test_straight_beats_three_of_a_kind() {
test(&["4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C"], &["3S 4D 2S 6D 5C"])
}

#[test]
#[ignore]
fn test_aces_can_end_a_straight_high() {
// aces can end a straight (10 J Q K A)
test(&["4S 5H 4C 8D 4H", "10D JH QS KD AC"], &["10D JH QS KD AC"])
}

#[test]
#[ignore]
fn test_aces_can_end_a_straight_low() {
// aces can start a straight (A 2 3 4 5)
test(&["4S 5H 4C 8D 4H", "4D AH 3S 2D 5C"], &["4D AH 3S 2D 5C"])
}

#[test]
#[ignore]
// both hands with a straight, tie goes to highest ranked card
test(&["4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H"], &["5S 7H 8S 9D 6H"])
}

#[test]
#[ignore]
fn test_straight_scoring() {
// even though an ace is usually high, a 5-high straight is the lowest-scoring straight
test(&["2H 3C 4D 5D 6H", "4S AH 3S 2D 5H"], &["2H 3C 4D 5D 6H"])
}

#[test]
#[ignore]
fn test_flush_beats_a_straight() {
test(&["4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S"], &["2S 4S 5S 6S 7S"])
}

#[test]
#[ignore]
// both hands have a flush, tie goes to high card, down to the last one if necessary
test(&["4H 7H 8H 9H 6H", "2S 4S 5S 6S 7S"], &["4H 7H 8H 9H 6H"])
}

#[test]
#[ignore]
fn test_full_house_beats_a_flush() {
test(&["3H 6H 7H 8H 5H", "4S 5C 4C 5D 4H"], &["4S 5C 4C 5D 4H"])
}

#[test]
#[ignore]
fn test_full_house_ranks() {
// both hands have a full house, tie goes to highest-ranked triplet
test(&["4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D"], &["5H 5S 5D 8S 8D"])
}

#[test]
#[ignore]
// with multiple decks, both hands have a full house with the same triplet, tie goes to the pair
test(&["5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D"], &["5H 5S 5D 9S 9D"])
}

#[test]
#[ignore]
fn test_four_of_a_kind_beats_full_house() {
test(&["4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C"], &["3S 3H 2S 3D 3C"])
}

#[test]
#[ignore]
fn test_four_of_a_kind_ranks() {
// both hands have four of a kind, tie goes to high quad
test(&["2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C"], &["4S 5H 5S 5D 5C"])
}

#[test]
#[ignore]
// with multiple decks, both hands with identical four of a kind, tie determined by kicker
test(&["3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C"], &["3S 3H 4S 3D 3C"])
}

#[test]
#[ignore]
fn test_straight_flush_beats_four_of_a_kind() {
test(&["4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S"], &["7S 8S 9S 6S 10S"])
}

#[test]
#[ignore]
fn test_straight_flush_ranks() {
// both hands have straight flush, tie goes to highest-ranked card
test(&["4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S"], &["5S 7S 8S 9S 6S"])
}``````
``````use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::HashSet;
use std::str::FromStr;

#[derive(Eq, PartialEq, Hash, Clone)]
pub enum Suit {
Clubs,
Diamonds,
Hearts,
}

#[derive(Eq, PartialEq, Hash, Clone)]
pub enum CardRank {
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace,
}

#[derive(Ord, PartialOrd, Eq, PartialEq)]
pub enum HandRank {
HighCard,
Pair,
TwoPairs,
ThreeOfAKind,
Straight,
Flush,
FullHouse,
FourOfAKind,
StraightFlush,
}

#[derive(Eq, PartialEq, Hash, Clone)]
pub struct Card {
pub rank: CardRank,
pub suit: Suit,
}

impl FromStr for Card {
type Err = ParseCardError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let rank = match s.chars().next().unwrap() {
'2' => CardRank::Two,
'3' => CardRank::Three,
'4' => CardRank::Four,
'5' => CardRank::Five,
'6' => CardRank::Six,
'7' => CardRank::Seven,
'8' => CardRank::Eight,
'9' => CardRank::Nine,
'1' => CardRank::Ten,
'J' => CardRank::Jack,
'Q' => CardRank::Queen,
'K' => CardRank::King,
'A' => CardRank::Ace,
_ => return Err(ParseCardError {}),
};

let suit = match s.chars().last().unwrap() {
'C' => Suit::Clubs,
'D' => Suit::Diamonds,
'H' => Suit::Hearts,
_ => return Err(ParseCardError {}),
};

Ok(Card { suit, rank })
}
}

#[derive(Debug)]
pub struct ParseCardError {}

/// Representation of a poker hand.
pub struct Hand(HashSet<Card>);

impl FromStr for Hand {
type Err = ParseHandError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.split_whitespace().map(|c| c.parse()).collect() {
Ok(cards) => Ok(Hand(cards)),
Err(_) => Err(ParseHandError {}),
}
}
}

#[derive(Debug)]
pub struct ParseHandError {}

// Given an array of string slices, return any of the same same string slices
// that represent winning hands.
pub fn winning_hands<'a>(hands: &[&'a str]) -> Option<Vec<&'a str>> {
struct HandInfo<'a> {
string: &'a str,
hand_rank: HandRank,
card_values: Vec<i8>,
}

let mut result = Vec::<&str>::new();

let all_hands: Vec<HandInfo> = hands
.iter()
.map(|&s| {
let hand: Hand = s.parse().unwrap();
let (hand_rank, card_values) = get_hand_rank(&hand);
HandInfo {
string: &s,
hand_rank,
card_values,
}
}).collect();

let mut hand_iterator = all_hands.into_iter();
let mut previous;

if let Some(first) = hand_iterator.next() {
result.push(first.string);
previous = first;

for current in hand_iterator {
match current.hand_rank.cmp(&previous.hand_rank) {
Ordering::Greater => {
result.clear();
result.push(current.string);
previous = current;
}
Ordering::Equal => match current.card_values.cmp(&previous.card_values) {
Ordering::Greater => {
result.clear();
result.push(current.string);
previous = current;
}
Ordering::Equal => {
result.push(current.string);
}
_ => {}
},
_ => {}
}
}
}

Some(result)
}

// Given a `Hand`, returns a `HandRank`, and a `Vec<i8>` of significant card
// values for purposes of comparing the hand to other hands of the same rank.
fn get_hand_rank(hand: &Hand) -> (HandRank, Vec<i8>) {
let mut card_rank_count: HashMap<i8, i8> = HashMap::new();

for card in hand.0.clone() {
*card_rank_count.entry(card.rank as i8).or_insert(0) += 1;
}

let mut card_values: Vec<i8> = card_rank_count
.clone()
.into_iter()
.map(|(k, _)| k as i8)
.collect();

card_values.sort_by(|a, b| match card_rank_count[&b].cmp(&card_rank_count[a]) {
Ordering::Equal => b.cmp(a),
ordering => ordering,
});

let straight = if card_values.len() == 5 {
let high_card = card_values.first().cloned().unwrap();
let low_card = card_values.last().cloned().unwrap();

if high_card == low_card + 4 {
card_values.truncate(1);
true
} else if high_card == CardRank::Ace as i8 && card_values.get(1).cloned().unwrap() == CardRank::Five as i8 {
card_values.clear();
card_values.push(CardRank::Two as i8 - 1);
true
} else {
false
}
} else {
false
};

let mut card_iterator = hand.0.iter();
let first_suit = card_iterator.next().cloned().unwrap().suit;
let flush = card_iterator.all(|c| c.suit == first_suit);

let rank_option = match (straight, flush) {
(true, false) => Some(HandRank::Straight),
(false, true) => Some(HandRank::Flush),
(true, true) => Some(HandRank::StraightFlush),
_ => None,
};

if let Some(rank) = rank_option {
return (rank, card_values);
}

let max_count = *card_rank_count.values().max().unwrap();

let rank = if max_count == 4 {
HandRank::FourOfAKind
} else if card_rank_count.len() == 2 {
HandRank::FullHouse
} else if max_count == 3 {
HandRank::ThreeOfAKind
} else if max_count == 2 {
let pair_count = card_rank_count
.iter()
.filter(|(_, &count)| count == 2)
.count();

match pair_count {
2 => HandRank::TwoPairs,
1 => HandRank::Pair,
_ => unreachable!(),
}
} else {
HandRank::HighCard
};

(rank, card_values)
}``````