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

# n0mn0m's solution

## to Poker in the Rust Track

Published at Nov 09 2020 · 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"])
}``````
``````/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
use std::cmp::{Ord, Ordering};
use std::collections::HashMap;

const CARD_VALUE: &[&str] = &[
"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A",
];

#[derive(PartialEq, PartialOrd, Eq, Debug)]
enum PokerRank {
StraightFlush(u8),
FourOfAKind(u8, u8),
FullHouse(u8, u8),
Flush(u8, u8, u8, u8, u8),
Straight(u8),
ThreeOfAKind(u8, u8, u8),
TwoPair(u8, u8, u8),
OnePair(u8, u8, u8, u8),
HighCard(u8, u8, u8, u8, u8),
}

impl PokerRank {
fn value(&self) -> Vec<u8> {
match self {
PokerRank::StraightFlush(one) => vec![8, *one],
PokerRank::FourOfAKind(one, two) => vec![7, *one, *two],
PokerRank::FullHouse(one, two) => vec![6, *one, *two],
PokerRank::Flush(one, two, three, four, five) => {
vec![5, *one, *two, *three, *four, *five]
}
PokerRank::Straight(one) => vec![4, *one],
PokerRank::ThreeOfAKind(one, two, three) => vec![3, *one, *two, *three],
PokerRank::TwoPair(one, two, three) => vec![2, *one, *two, *three],
PokerRank::OnePair(one, two, three, four) => vec![1, *one, *two, *three, *four],
PokerRank::HighCard(one, two, three, four, five) => {
vec![0, *one, *two, *three, *four, *five]
}
}
}
}

impl Ord for PokerRank {
fn cmp(&self, other: &Self) -> Ordering {
self.value()
.iter()
.zip(other.value())
.map(|(a, b)| a.cmp(&b))
.find(|result| *result != Ordering::Equal)
.unwrap_or(Ordering::Equal)
}
}

#[derive(Debug, PartialEq)]
struct Card(u8, char);

fn to_cards(hand: &str) -> Vec<Card> {
hand.split_whitespace()
.map(|card_str| {
let (value, suit) = card_str.split_at(card_str.len() - 1);

Card(
CARD_VALUE
.iter()
.position(|card_value| *card_value == value)
.unwrap() as u8
+ 1,
suit.chars().next().unwrap(),
)
})
.collect::<Vec<_>>()
}

fn generate_value_pairs(cards: &[Card]) -> Vec<(u8, i32)> {
let mut value_pairs: Vec<(u8, i32)> = cards
.iter()
.fold(HashMap::new(), |mut acc, item| {
*acc.entry(item.0).or_insert(0) += 1;
acc
})
.into_iter()
.collect::<Vec<_>>();

value_pairs.sort_by(|a, b| {
if a.1 == b.1 {
b.0.cmp(&a.0)
} else {
b.1.cmp(&a.1)
}
});

value_pairs
}

fn is_flush(cards: &[Card]) -> bool {
let suit = cards.first().unwrap().1;
cards.iter().all(|card| card.1 == suit)
}

fn is_straight(cards: &[Card]) -> bool {
let last_index = CARD_VALUE.len() as u8;

cards.windows(2).all(|items| {
let first_index = items.first().unwrap().0;
let second_index = items.last().unwrap().0;

(first_index - second_index) == 1 || (first_index == last_index && second_index == 4)
})
}

fn score_hand(hand: &str) -> PokerRank {
let mut cards = to_cards(hand);
cards.sort_by(|a, b| b.0.cmp(&a.0));

let is_flush = is_flush(&cards);
let is_straight = is_straight(&cards);

// demote ace low
if is_straight && cards[0].0 as usize == CARD_VALUE.len() && cards.last().unwrap().0 == 1 {
cards[0].0 = 0;
}

match generate_value_pairs(&cards) {
x if x[0].1 == 4 => PokerRank::FourOfAKind(x[0].0, x[1].0),
x if x[0].1 == 3 && x[1].1 == 2 => PokerRank::FullHouse(x[0].0, x[1].0),
x if x[0].1 == 3 => PokerRank::ThreeOfAKind(x[0].0, x[1].0, x[2].0),
x if x[0].1 == 2 && x[1].1 == 2 => PokerRank::TwoPair(x[0].0, x[1].0, x[2].0),
x if x[0].1 == 2 => PokerRank::OnePair(x[0].0, x[1].0, x[2].0, x[3].0),
// if not a value pair rank move into full hand.
_x if is_straight && is_flush => PokerRank::StraightFlush(cards[0].0),
_x if is_flush => {
PokerRank::Flush(cards[0].0, cards[1].0, cards[2].0, cards[3].0, cards[4].0)
}
_x if is_straight => PokerRank::Straight(cards[0].0),
_ => PokerRank::HighCard(cards[0].0, cards[1].0, cards[2].0, cards[3].0, cards[4].0),
}
}

pub fn winning_hands<'a>(hands: &'a [&'a str]) -> Option<Vec<&'a str>> {
let hand_values = hands.iter().fold(HashMap::new(), |mut acc, hand| {
acc.insert(*hand, score_hand(*hand));
acc
});

let max_hand = hand_values.values().max()?;

Some(
hand_values
.iter()
.filter(|(_, hand_value)| **hand_value == *max_hand)
.map(|(hand, _)| *hand)
.collect::<Vec<_>>(),
)
}``````