Solve poker
This commit is contained in:
parent
0227dd52fd
commit
2297e09365
10 changed files with 991 additions and 3 deletions
|
@ -40,11 +40,11 @@
|
|||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1729265718,
|
||||
"narHash": "sha256-4HQI+6LsO3kpWTYuVGIzhJs1cetFcwT7quWCk/6rqeo=",
|
||||
"lastModified": 1729658218,
|
||||
"narHash": "sha256-9Rg+AqLqvqqJniP/OQB3GtgXoAd8IlazsHp97va042Y=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "ccc0c2126893dd20963580b6478d1a10a4512185",
|
||||
"rev": "dfffb2e7a52d29a0ef8e21ec8a0f30487b227f1a",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
|
36
rust/poker/.exercism/config.json
Normal file
36
rust/poker/.exercism/config.json
Normal file
|
@ -0,0 +1,36 @@
|
|||
{
|
||||
"authors": [
|
||||
"coriolinus"
|
||||
],
|
||||
"contributors": [
|
||||
"Baelyk",
|
||||
"CGMossa",
|
||||
"cwhakes",
|
||||
"efx",
|
||||
"elektronaut0815",
|
||||
"ErikSchierboom",
|
||||
"lutostag",
|
||||
"nfiles",
|
||||
"PaulDance",
|
||||
"petertseng",
|
||||
"rofrol",
|
||||
"stringparser",
|
||||
"xakon",
|
||||
"ZapAnton"
|
||||
],
|
||||
"files": {
|
||||
"solution": [
|
||||
"src/lib.rs",
|
||||
"Cargo.toml"
|
||||
],
|
||||
"test": [
|
||||
"tests/poker.rs"
|
||||
],
|
||||
"example": [
|
||||
".meta/example.rs"
|
||||
]
|
||||
},
|
||||
"blurb": "Pick the best hand(s) from a list of poker hands.",
|
||||
"source": "Inspired by the training course from Udacity.",
|
||||
"source_url": "https://www.udacity.com/course/design-of-computer-programs--cs212"
|
||||
}
|
1
rust/poker/.exercism/metadata.json
Normal file
1
rust/poker/.exercism/metadata.json
Normal file
|
@ -0,0 +1 @@
|
|||
{"track":"rust","exercise":"poker","id":"3a4bc5ddba7f42448ca982a3ca090575","url":"https://exercism.org/tracks/rust/exercises/poker","handle":"averywinters","is_requester":true,"auto_approve":false}
|
8
rust/poker/.gitignore
vendored
Normal file
8
rust/poker/.gitignore
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
**/*.rs.bk
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
|
||||
Cargo.lock
|
7
rust/poker/Cargo.toml
Normal file
7
rust/poker/Cargo.toml
Normal file
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
edition = "2021"
|
||||
name = "poker"
|
||||
version = "1.1.0"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.86"
|
86
rust/poker/HELP.md
Normal file
86
rust/poker/HELP.md
Normal file
|
@ -0,0 +1,86 @@
|
|||
# Help
|
||||
|
||||
## Running the tests
|
||||
|
||||
Execute the tests with:
|
||||
|
||||
```bash
|
||||
$ 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 _only ignored_ tests without editing the tests source file, use:
|
||||
|
||||
```bash
|
||||
$ cargo test -- --ignored
|
||||
```
|
||||
|
||||
If you are using Rust 1.51 or later, you can run _all_ tests with
|
||||
|
||||
```bash
|
||||
$ cargo test -- --include-ignored
|
||||
```
|
||||
|
||||
To run a specific test, for example `some_test`, you can use:
|
||||
|
||||
```bash
|
||||
$ cargo test some_test
|
||||
```
|
||||
|
||||
If the specific test is ignored, use:
|
||||
|
||||
```bash
|
||||
$ cargo test some_test -- --ignored
|
||||
```
|
||||
|
||||
To learn more about Rust tests refer to the online [test documentation][rust-tests].
|
||||
|
||||
[rust-tests]: https://doc.rust-lang.org/book/ch11-02-running-tests.html
|
||||
|
||||
## Submitting your solution
|
||||
|
||||
You can submit your solution using the `exercism submit src/lib.rs Cargo.toml` command.
|
||||
This command will upload your solution to the Exercism website and print the solution page's URL.
|
||||
|
||||
It's possible to submit an incomplete solution which allows you to:
|
||||
|
||||
- See how others have completed the exercise
|
||||
- Request help from a mentor
|
||||
|
||||
## Need to get help?
|
||||
|
||||
If you'd like help solving the exercise, check the following pages:
|
||||
|
||||
- The [Rust track's documentation](https://exercism.org/docs/tracks/rust)
|
||||
- The [Rust track's programming category on the forum](https://forum.exercism.org/c/programming/rust)
|
||||
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
|
||||
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
|
||||
|
||||
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
|
||||
|
||||
## Rust Installation
|
||||
|
||||
Refer to the [exercism help page][help-page] for Rust installation and learning
|
||||
resources.
|
||||
|
||||
## 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 GitHub [track repository][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].
|
||||
|
||||
## Submitting Incomplete Solutions
|
||||
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
|
||||
|
||||
[help-page]: https://exercism.org/tracks/rust/learning
|
||||
[github]: https://github.com/exercism/rust
|
||||
[contribution guide]: https://exercism.org/docs/community/contributors
|
10
rust/poker/HINTS.md
Normal file
10
rust/poker/HINTS.md
Normal file
|
@ -0,0 +1,10 @@
|
|||
# Hints
|
||||
|
||||
## General
|
||||
|
||||
- Ranking a list of poker hands can be considered a sorting problem.
|
||||
- Rust provides the [sort](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.sort) method for `Vec<T> where T: Ord`.
|
||||
- [`Ord` types](https://doc.rust-lang.org/std/cmp/trait.Ord.html) form a [total order](https://en.wikipedia.org/wiki/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](https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html) 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`.
|
40
rust/poker/README.md
Normal file
40
rust/poker/README.md
Normal file
|
@ -0,0 +1,40 @@
|
|||
# Poker
|
||||
|
||||
Welcome to Poker on Exercism's Rust Track.
|
||||
If you need help running the tests or submitting your code, check out `HELP.md`.
|
||||
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
|
||||
|
||||
## Instructions
|
||||
|
||||
Pick the best hand(s) from a list of poker hands.
|
||||
|
||||
See [wikipedia][poker-hands] for an overview of poker hands.
|
||||
|
||||
[poker-hands]: https://en.wikipedia.org/wiki/List_of_poker_hands
|
||||
|
||||
## Source
|
||||
|
||||
### Created by
|
||||
|
||||
- @coriolinus
|
||||
|
||||
### Contributed to by
|
||||
|
||||
- @Baelyk
|
||||
- @CGMossa
|
||||
- @cwhakes
|
||||
- @efx
|
||||
- @elektronaut0815
|
||||
- @ErikSchierboom
|
||||
- @lutostag
|
||||
- @nfiles
|
||||
- @PaulDance
|
||||
- @petertseng
|
||||
- @rofrol
|
||||
- @stringparser
|
||||
- @xakon
|
||||
- @ZapAnton
|
||||
|
||||
### Based on
|
||||
|
||||
Inspired by the training course from Udacity. - https://www.udacity.com/course/design-of-computer-programs--cs212
|
493
rust/poker/src/lib.rs
Normal file
493
rust/poker/src/lib.rs
Normal file
|
@ -0,0 +1,493 @@
|
|||
use ::{
|
||||
anyhow::{bail, ensure, Context, Error, Result},
|
||||
std::{
|
||||
array::from_fn,
|
||||
cmp::Reverse,
|
||||
fmt::{Display, Formatter, Result as FmtResult},
|
||||
iter::Fuse,
|
||||
mem::replace,
|
||||
num::NonZeroUsize,
|
||||
str::FromStr,
|
||||
},
|
||||
};
|
||||
|
||||
/// 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.
|
||||
pub fn winning_hands<'a>(hands: &[&'a str]) -> Vec<&'a str> {
|
||||
let mut hands: Vec<(HandRank, &'a str)> = hands
|
||||
.iter()
|
||||
.map(|&s| {
|
||||
let hand: Hand = s.parse()?;
|
||||
let rank = hand.rank();
|
||||
Ok((rank, s))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.expect("all hands should be valid");
|
||||
hands.sort_by_key(|&(rank, _)| Reverse(rank));
|
||||
let Some(&(best_rank, _)) = hands[..].first() else {
|
||||
return vec![];
|
||||
};
|
||||
hands
|
||||
.into_iter()
|
||||
.map_while(|(rank, s)| {
|
||||
let is_best = rank == best_rank;
|
||||
is_best.then_some(s)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
struct Hand {
|
||||
highest_cards: [Card; 5],
|
||||
}
|
||||
|
||||
impl Hand {
|
||||
fn try_from_cards(cards: [Card; 5]) -> Result<Self> {
|
||||
let mut highest_cards = cards;
|
||||
// Stability doesn't matter, equal cards are indistinguishable.
|
||||
highest_cards.sort_unstable_by_key(|&c| Reverse(c));
|
||||
let duplicate_card = highest_cards.windows(2).find_map(|window| {
|
||||
let [a, b] = window else {
|
||||
panic!("bad window size");
|
||||
};
|
||||
let is_duplicate = a == b;
|
||||
is_duplicate.then_some(a)
|
||||
});
|
||||
if let Some(card) = duplicate_card {
|
||||
bail!("hand contained duplicate card: {}", card);
|
||||
}
|
||||
Ok(Self { highest_cards })
|
||||
}
|
||||
|
||||
fn rank(&self) -> HandRank {
|
||||
use Run::*;
|
||||
|
||||
let straight_rank = self.straight_rank();
|
||||
let flush_ranks = self.flush_ranks();
|
||||
let runs = self.runs();
|
||||
|
||||
match (straight_rank, flush_ranks, runs) {
|
||||
(Some(highest_rank), Some(_), _) => {
|
||||
HandRank::StraightFlush(StraightFlush { highest_rank })
|
||||
}
|
||||
(
|
||||
_,
|
||||
_,
|
||||
[Some(Quadruplet(quadruplet_rank)), Some(Single(kicker_rank)), None, None, None],
|
||||
) => HandRank::FourOfAKind(FourOfAKind {
|
||||
quadruplet_rank,
|
||||
kicker_rank,
|
||||
}),
|
||||
(_, _, [Some(Triplet(triplet_rank)), Some(Pair(pair_rank)), None, None, None]) => {
|
||||
HandRank::FullHouse(FullHouse {
|
||||
triplet_rank,
|
||||
pair_rank,
|
||||
})
|
||||
}
|
||||
(_, Some(highest_ranks), _) => HandRank::Flush(Flush { highest_ranks }),
|
||||
(Some(highest_rank), _, _) => HandRank::Straight(Straight { highest_rank }),
|
||||
(_, _, [Some(Triplet(triplet_rank)), kickers @ .., None, None]) => {
|
||||
let highest_kicker_ranks = kickers.map(|run| run.expect("bad kickers").rank());
|
||||
HandRank::ThreeOfAKind(ThreeOfAKind {
|
||||
triplet_rank,
|
||||
highest_kicker_ranks,
|
||||
})
|
||||
}
|
||||
(_, _, [pairs @ .., Some(Single(kicker_rank)), None, None]) => {
|
||||
let highest_pair_ranks = pairs.map(|run| run.expect("bad pairs").rank());
|
||||
HandRank::TwoPair(TwoPair {
|
||||
highest_pair_ranks,
|
||||
kicker_rank,
|
||||
})
|
||||
}
|
||||
(_, _, [Some(Pair(pair_rank)), kickers @ .., None]) => {
|
||||
let highest_kicker_ranks = kickers.map(|run| run.expect("bad kickers").rank());
|
||||
HandRank::OnePair(OnePair {
|
||||
pair_rank,
|
||||
highest_kicker_ranks,
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
let highest_ranks = self.highest_cards.map(|card| card.rank);
|
||||
HandRank::HighCard(HighCard { highest_ranks })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn flush_ranks(&self) -> Option<[Rank; 5]> {
|
||||
let is_flush = self.highest_cards.windows(2).all(|window| {
|
||||
let [a, b] = window else {
|
||||
panic!("bad window length");
|
||||
};
|
||||
a.suit == b.suit
|
||||
});
|
||||
let highest_ranks = self.highest_cards.map(|card| card.rank);
|
||||
is_flush.then_some(highest_ranks)
|
||||
}
|
||||
|
||||
fn straight_rank(&self) -> Option<Rank> {
|
||||
let is_straight = self.highest_cards.windows(2).all(|window| {
|
||||
let [a, b] = window else {
|
||||
panic!("bad window length");
|
||||
};
|
||||
a.rank.next_lower() == Some(b.rank) || a.rank == Rank::Ace && b.rank == Rank::Five
|
||||
});
|
||||
let highest_rank = self.highest_cards[0].rank;
|
||||
let highest_rank = {
|
||||
let next_highest_rank = self.highest_cards[1].rank;
|
||||
let is_ace_low = highest_rank == Rank::Ace && next_highest_rank == Rank::Five;
|
||||
if !is_ace_low {
|
||||
highest_rank
|
||||
} else {
|
||||
next_highest_rank
|
||||
}
|
||||
};
|
||||
is_straight.then_some(highest_rank)
|
||||
}
|
||||
|
||||
fn runs(&self) -> [Option<Run>; 5] {
|
||||
use Run::*;
|
||||
let mut runs = self
|
||||
.highest_cards
|
||||
.iter()
|
||||
.map(|card| card.rank)
|
||||
.runs()
|
||||
.map(|(count, rank)| match count.get() {
|
||||
4 => Quadruplet(rank),
|
||||
3 => Triplet(rank),
|
||||
2 => Pair(rank),
|
||||
1 => Single(rank),
|
||||
_ => panic!("hand contained imposibly long run"),
|
||||
})
|
||||
.fuse();
|
||||
let mut runs = from_fn(|_| runs.next());
|
||||
runs.sort_by_key(|&run| Reverse(run));
|
||||
runs
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Hand {
|
||||
type Err = Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
let mut cards = s.split_whitespace();
|
||||
macro_rules! arr_5 {
|
||||
($e:expr$(,)?) => {
|
||||
[$e, $e, $e, $e, $e]
|
||||
};
|
||||
}
|
||||
let five_cards = arr_5![{
|
||||
cards
|
||||
.next()
|
||||
.with_context(|| format!("hand with less than five cards found in string: {}", s))?
|
||||
.parse()
|
||||
.with_context(|| format!("invalid hand found in string: {}", s))?
|
||||
}];
|
||||
ensure!(
|
||||
cards.next().is_none(),
|
||||
"hand with more than five cards found in string: {}",
|
||||
s
|
||||
);
|
||||
Self::try_from_cards(five_cards)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Hand {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
write!(
|
||||
f,
|
||||
"{} {} {} {} {}",
|
||||
self.highest_cards[0],
|
||||
self.highest_cards[1],
|
||||
self.highest_cards[2],
|
||||
self.highest_cards[3],
|
||||
self.highest_cards[4]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
enum HandRank {
|
||||
HighCard(HighCard),
|
||||
OnePair(OnePair),
|
||||
TwoPair(TwoPair),
|
||||
ThreeOfAKind(ThreeOfAKind),
|
||||
Straight(Straight),
|
||||
Flush(Flush),
|
||||
FullHouse(FullHouse),
|
||||
FourOfAKind(FourOfAKind),
|
||||
StraightFlush(StraightFlush),
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct HighCard {
|
||||
highest_ranks: [Rank; 5],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct OnePair {
|
||||
pair_rank: Rank,
|
||||
highest_kicker_ranks: [Rank; 3],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct TwoPair {
|
||||
highest_pair_ranks: [Rank; 2],
|
||||
kicker_rank: Rank,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct ThreeOfAKind {
|
||||
triplet_rank: Rank,
|
||||
highest_kicker_ranks: [Rank; 2],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct Straight {
|
||||
highest_rank: Rank,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct Flush {
|
||||
highest_ranks: [Rank; 5],
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct FullHouse {
|
||||
triplet_rank: Rank,
|
||||
pair_rank: Rank,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct FourOfAKind {
|
||||
quadruplet_rank: Rank,
|
||||
kicker_rank: Rank,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct StraightFlush {
|
||||
highest_rank: Rank,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
enum Run {
|
||||
Single(Rank),
|
||||
Pair(Rank),
|
||||
Triplet(Rank),
|
||||
Quadruplet(Rank),
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn rank(&self) -> Rank {
|
||||
use Run::*;
|
||||
match *self {
|
||||
Single(rank) | Pair(rank) | Triplet(rank) | Quadruplet(rank) => rank,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait IteratorExt: Iterator {
|
||||
fn runs(self) -> Runs<Self>
|
||||
where
|
||||
Self: Iterator + Sized,
|
||||
Self::Item: Eq,
|
||||
{
|
||||
let inner = self.fuse();
|
||||
let last = None;
|
||||
Runs { inner, last }
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> IteratorExt for I where I: Iterator + ?Sized {}
|
||||
|
||||
struct Runs<I>
|
||||
where
|
||||
I: Iterator,
|
||||
{
|
||||
inner: Fuse<I>,
|
||||
last: Option<(NonZeroUsize, I::Item)>,
|
||||
}
|
||||
|
||||
impl<I> Iterator for Runs<I>
|
||||
where
|
||||
I: Iterator,
|
||||
I::Item: Eq,
|
||||
{
|
||||
type Item = (NonZeroUsize, I::Item);
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
let next = self.inner.next();
|
||||
match (next, &mut self.last) {
|
||||
(Some(next), Some((count, last))) if next == *last => {
|
||||
*count = count.saturating_add(1);
|
||||
}
|
||||
(Some(next), Some((count, last))) => {
|
||||
let count = replace(count, NonZeroUsize::MIN);
|
||||
let last = replace(last, next);
|
||||
break Some((count, last));
|
||||
}
|
||||
(Some(next), last @ None) => {
|
||||
*last = Some((NonZeroUsize::MIN, next));
|
||||
}
|
||||
(None, last @ Some(_)) => {
|
||||
break last.take();
|
||||
}
|
||||
(None, None) => {
|
||||
break None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
struct Card {
|
||||
rank: Rank,
|
||||
suit: Suit,
|
||||
}
|
||||
|
||||
impl FromStr for Card {
|
||||
type Err = Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
let (last_idx, _) = s
|
||||
.char_indices()
|
||||
.last()
|
||||
.with_context(|| format!("card missing rank found in string: {}", s))?;
|
||||
let (rank, suit) = s.split_at(last_idx);
|
||||
ensure!(!suit.is_empty(), "card missing suit found in string: {}", s);
|
||||
let rank = rank
|
||||
.parse()
|
||||
.with_context(|| format!("invalid card found in string: {}", s))?;
|
||||
let suit = suit
|
||||
.parse()
|
||||
.with_context(|| format!("invalid card found in string: {}", s))?;
|
||||
Ok(Self { suit, rank })
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Card {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
write!(f, "{}{}", self.rank, self.suit)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
enum Suit {
|
||||
Spades,
|
||||
Hearts,
|
||||
Diamonds,
|
||||
Clubs,
|
||||
}
|
||||
|
||||
impl FromStr for Suit {
|
||||
type Err = Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
use Suit::*;
|
||||
let suit = match s {
|
||||
"S" => Spades,
|
||||
"H" => Hearts,
|
||||
"D" => Diamonds,
|
||||
"C" => Clubs,
|
||||
_ => bail!("invalid suit found in string: {}", s),
|
||||
};
|
||||
Ok(suit)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Suit {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
use Suit::*;
|
||||
let s = match *self {
|
||||
Spades => "S",
|
||||
Hearts => "H",
|
||||
Diamonds => "D",
|
||||
Clubs => "C",
|
||||
};
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
|
||||
enum Rank {
|
||||
Two,
|
||||
Three,
|
||||
Four,
|
||||
Five,
|
||||
Six,
|
||||
Seven,
|
||||
Eight,
|
||||
Nine,
|
||||
Ten,
|
||||
Jack,
|
||||
Queen,
|
||||
King,
|
||||
Ace,
|
||||
}
|
||||
|
||||
impl Rank {
|
||||
fn next_lower(&self) -> Option<Rank> {
|
||||
use Rank::*;
|
||||
match *self {
|
||||
Two => None,
|
||||
Three => Some(Two),
|
||||
Four => Some(Three),
|
||||
Five => Some(Four),
|
||||
Six => Some(Five),
|
||||
Seven => Some(Six),
|
||||
Eight => Some(Seven),
|
||||
Nine => Some(Eight),
|
||||
Ten => Some(Nine),
|
||||
Jack => Some(Ten),
|
||||
Queen => Some(Jack),
|
||||
King => Some(Queen),
|
||||
Ace => Some(King),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Rank {
|
||||
type Err = Error;
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
use Rank::*;
|
||||
let rank = match s {
|
||||
"2" => Two,
|
||||
"3" => Three,
|
||||
"4" => Four,
|
||||
"5" => Five,
|
||||
"6" => Six,
|
||||
"7" => Seven,
|
||||
"8" => Eight,
|
||||
"9" => Nine,
|
||||
"10" => Ten,
|
||||
"J" => Jack,
|
||||
"Q" => Queen,
|
||||
"K" => King,
|
||||
"A" => Ace,
|
||||
_ => bail!("invalid rank found in string: {}", s),
|
||||
};
|
||||
Ok(rank)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Rank {
|
||||
fn fmt(&self, f: &mut Formatter) -> FmtResult {
|
||||
use Rank::*;
|
||||
let s = match *self {
|
||||
Two => "2",
|
||||
Three => "3",
|
||||
Four => "4",
|
||||
Five => "5",
|
||||
Six => "6",
|
||||
Seven => "7",
|
||||
Eight => "8",
|
||||
Nine => "9",
|
||||
Ten => "10",
|
||||
Jack => "J",
|
||||
Queen => "Q",
|
||||
King => "K",
|
||||
Ace => "A",
|
||||
};
|
||||
f.write_str(s)
|
||||
}
|
||||
}
|
307
rust/poker/tests/poker.rs
Normal file
307
rust/poker/tests/poker.rs
Normal file
|
@ -0,0 +1,307 @@
|
|||
use poker::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn single_hand_always_wins() {
|
||||
let input = &["4S 5S 7H 8D JC"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S 5S 7H 8D JC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highest_card_out_of_all_hands_wins() {
|
||||
let input = &["4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 4S 5D 6H JH"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tie_has_multiple_winners() {
|
||||
let input = &[
|
||||
"4D 5S 6S 8D 3C",
|
||||
"2S 4C 7S 9H 10H",
|
||||
"3S 4S 5D 6H JH",
|
||||
"3H 4H 5C 6C JD",
|
||||
];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 4S 5D 6H JH", "3H 4H 5C 6C JD"]
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_hands_with_the_same_high_cards_tie_compares_next_highest_ranked_down_to_last_card() {
|
||||
let input = &["3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 5H 6S 8D 7H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn winning_high_card_hand_also_has_the_lowest_card() {
|
||||
let input = &["2S 5H 6S 8D 7H", "3S 4D 6D 8C 7S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2S 5H 6S 8D 7H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_pair_beats_high_card() {
|
||||
let input = &["4S 5H 6C 8D KH", "2S 4H 6S 4D JH"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2S 4H 6S 4D JH"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highest_pair_wins() {
|
||||
let input = &["4S 2H 6S 2D JH", "2S 4H 6C 4D JD"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2S 4H 6C 4D JD"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_the_same_pair_high_card_wins() {
|
||||
let input = &["4H 4S AH JC 3D", "4C 4D AS 5D 6C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4H 4S AH JC 3D"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_pairs_beats_one_pair() {
|
||||
let input = &["2S 8H 6S 8D JH", "4S 5H 4C 8C 5C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S 5H 4C 8C 5C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_two_pairs_highest_ranked_pair_wins() {
|
||||
let input = &["2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2S 8H 2D 8D 3H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_two_pairs_with_the_same_highest_ranked_pair_tie_goes_to_low_pair() {
|
||||
let input = &["2S QS 2C QD JH", "JD QH JS 8D QC"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["JD QH JS 8D QC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_two_identically_ranked_pairs_tie_goes_to_remaining_card_kicker() {
|
||||
let input = &["JD QH JS 8D QC", "JS QS JC 2D QD"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["JD QH JS 8D QC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_two_pairs_that_add_to_the_same_value_win_goes_to_highest_pair() {
|
||||
let input = &["6S 6H 3S 3H AS", "7H 7S 2H 2S AC"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["7H 7S 2H 2S AC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_pairs_first_ranked_by_largest_pair() {
|
||||
let input = &["5C 2S 5S 4H 4C", "6S 2S 6H 7C 2C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["6S 2S 6H 7C 2C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_of_a_kind_beats_two_pair() {
|
||||
let input = &["2S 8H 2H 8D JH", "4S 5H 4C 8S 4H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S 5H 4C 8S 4H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_three_of_a_kind_tie_goes_to_highest_ranked_triplet() {
|
||||
let input = &["2S 2H 2C 8D JH", "4S AH AS 8C AD"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S AH AS 8C AD"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_multiple_decks_two_players_can_have_same_three_of_a_kind_ties_go_to_highest_remaining_cards(
|
||||
) {
|
||||
let input = &["5S AH AS 7C AD", "4S AH AS 8C AD"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S AH AS 8C AD"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_straight_beats_three_of_a_kind() {
|
||||
let input = &["4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 4D 2S 6D 5C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_can_end_a_straight_10_j_q_k_a() {
|
||||
let input = &["4S 5H 4C 8D 4H", "10D JH QS KD AC"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["10D JH QS KD AC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_can_start_a_straight_a_2_3_4_5() {
|
||||
let input = &["4S 5H 4C 8D 4H", "4D AH 3S 2D 5C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4D AH 3S 2D 5C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_cannot_be_in_the_middle_of_a_straight_q_k_a_2_3() {
|
||||
let input = &["2C 3D 7H 5H 2S", "QS KH AC 2D 3S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2C 3D 7H 5H 2S"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_with_a_straight_tie_goes_to_highest_ranked_card() {
|
||||
let input = &["4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["5S 7H 8S 9D 6H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_though_an_ace_is_usually_high_a_5_high_straight_is_the_lowest_scoring_straight() {
|
||||
let input = &["2H 3C 4D 5D 6H", "4S AH 3S 2D 5H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2H 3C 4D 5D 6H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flush_beats_a_straight() {
|
||||
let input = &["4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2S 4S 5S 6S 7S"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_a_flush_tie_goes_to_high_card_down_to_the_last_one_if_necessary() {
|
||||
let input = &["2H 7H 8H 9H 6H", "3S 5S 6S 7S 8S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2H 7H 8H 9H 6H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_house_beats_a_flush() {
|
||||
let input = &["3H 6H 7H 8H 5H", "4S 5H 4C 5D 4H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S 5H 4C 5D 4H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_a_full_house_tie_goes_to_highest_ranked_triplet() {
|
||||
let input = &["4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["5H 5S 5D 8S 8D"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_multiple_decks_both_hands_have_a_full_house_with_the_same_triplet_tie_goes_to_the_pair() {
|
||||
let input = &["5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["5H 5S 5D 9S 9D"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_of_a_kind_beats_a_full_house() {
|
||||
let input = &["4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 3H 2S 3D 3C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_four_of_a_kind_tie_goes_to_high_quad() {
|
||||
let input = &["2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4S 5H 5S 5D 5C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_multiple_decks_both_hands_with_identical_four_of_a_kind_tie_determined_by_kicker() {
|
||||
let input = &["3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["3S 3H 4S 3D 3C"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straight_flush_beats_four_of_a_kind() {
|
||||
let input = &["4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["7S 8S 9S 6S 10S"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_can_end_a_straight_flush_10_j_q_k_a() {
|
||||
let input = &["KC AH AS AD AC", "10C JC QC KC AC"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["10C JC QC KC AC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_can_start_a_straight_flush_a_2_3_4_5() {
|
||||
let input = &["KS AH AS AD AC", "4H AH 3H 2H 5H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["4H AH 3H 2H 5H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aces_cannot_be_in_the_middle_of_a_straight_flush_q_k_a_2_3() {
|
||||
let input = &["2C AC QC 10C KC", "QH KH AH 2H 3H"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2C AC QC 10C KC"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_hands_have_a_straight_flush_tie_goes_to_highest_ranked_card() {
|
||||
let input = &["4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["5S 7S 8S 9S 6S"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn even_though_an_ace_is_usually_high_a_5_high_straight_flush_is_the_lowest_scoring_straight_flush()
|
||||
{
|
||||
let input = &["2H 3H 4H 5H 6H", "4D AD 3D 2D 5D"];
|
||||
let output = winning_hands(input).into_iter().collect::<HashSet<_>>();
|
||||
let expected = ["2H 3H 4H 5H 6H"].into_iter().collect::<HashSet<_>>();
|
||||
assert_eq!(output, expected);
|
||||
}
|
Loading…
Reference in a new issue