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

# lnds's solution

## to Poker in the Rust Track

Published at Dec 30 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 are 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"])
}``````

### src/lib.rs

``````use itertools::Itertools;

pub fn winning_hands<'a>(hands: &[&'a str]) -> Option<Vec<&'a str>> {
let hands = hands
.iter()
.map(|hand| {
let pokerhand = PokerHand::new(
hand.split_whitespace()
.flat_map(|card| Card::new(card))
.collect::<Vec<Card>>()
.as_slice(),
);

(pokerhand, *hand)
})
.sorted_by(|x, y| y.cmp(x))
.collect::<Vec<(PokerHand, &'a str)>>();
if hands.iter().any(|(hand, _)| *hand == PokerHand::Invalid) {
None
} else {
let winner = &hands[0].0;
Some(
hands
.iter()
.take_while(|hand| hand.0 == *winner) // for ties
.map(|h| h.1)
.collect(),
)
}
}

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

impl PokerHand {
fn new(cards: &[Card]) -> Self {
if cards.len() != 5 {
return PokerHand::Invalid;
}

let grouped_cards = cards
.iter()
.sorted_by_key(|c| c.0)
.group_by(|&c| c.0)
.into_iter()
.map(|(_, g)| g.map(|c| c.0).collect())
.sorted_by_key(|v: &Vec<u8>| v.len())
.collect::<Vec<Vec<u8>>>();
let clasi = &grouped_cards
.iter()
.map(|v| v.len())
.collect::<Vec<usize>>();
match &clasi[..] {
[_, 4] => PokerHand::FourOfAKind(grouped_cards[1][0], grouped_cards[0][0]),
[2, 3] => PokerHand::FullHouse(grouped_cards[1][0], grouped_cards[0][0]),
[_, _, 3] => PokerHand::ThreeOfAKind(
grouped_cards[2][0],
grouped_cards[1][0],
grouped_cards[0][0],
),
[_, 2, 2] => PokerHand::TwoPair(
grouped_cards[2][0],
grouped_cards[1][0],
grouped_cards[0][0],
),
[_, _, _, 2] => PokerHand::OnePair(
grouped_cards[3][0],
grouped_cards[0][0],
grouped_cards[0][0],
grouped_cards[0][0],
),
_ => {
// can't find groups, so see if we have straights or flush
let cards: Vec<Card> = cards.iter().sorted_by(|x, y| y.cmp(x)).cloned().collect();
let straight = cards
.windows(2)
.all(|w| w[0].0 == w[1].0 + 1 || w[0].0 == 14 && w[1].0 == 5);
let flush = cards.iter().all(|c| c.1 == cards[0].1);

if !straight && !flush {
PokerHand::HighCard(cards[0].0, cards[1].0, cards[2].0, cards[3].0, cards[4].0)
} else {
// fix situation when we have an ace in cards
let max: u8 = cards
.iter()
.map(|c| if c.0 == 14 { 1 } else { c.0 })
.max()
.unwrap();

if straight && flush {
PokerHand::StraightFlush(max)
} else if straight {
PokerHand::Straight(max)
} else {
PokerHand::Flush(max)
}
}
}
}
}
}

#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
struct Card(u8, char);

impl Card {
fn new(card: &str) -> Option<Card> {
let value = match &card[0..card.len() - 1] {
"A" => 14,
"J" => 11,
"Q" => 12,
"K" => 13,
s => s.parse().ok().filter(|&x| x >= 2 && x <= 10)?,
};
let suite = card.chars().last().filter(|&s| s == 'H' || s == 'D' || s == 'S' || s == 'C')?;
Some(Card(value, suite))
}
}

#[test]
fn test_invalid_hand() {
assert!(winning_hands(&[""]).is_none());
assert!(winning_hands(&["4S 20S AS AH 2C"]).is_none());
assert!(winning_hands(&["4S 1S AS AH 2C"]).is_none());
assert!(winning_hands(&["4S 1S AH 2C"]).is_none());
assert!(winning_hands(&["4S 2S AS AH 2C"]).is_some());
assert!(winning_hands(&["4S 2s AS AH 2C"]).is_none());
assert!(winning_hands(&["4Z 2s AS AH 2C"]).is_none());
assert!(winning_hands(&["4SASAH2C10D"]).is_none());
}``````

### Cargo.toml

``````[package]
edition = "2018"
name = "poker"
version = "1.1.0"

[dependencies]
itertools = "0.8.2"``````