Skip to content

Instantly share code, notes, and snippets.

@sahuguet
Last active March 13, 2017 19:54
Show Gist options
  • Save sahuguet/e8d970f83811fd9264c1f702a838ffb5 to your computer and use it in GitHub Desktop.
Save sahuguet/e8d970f83811fd9264c1f702a838ffb5 to your computer and use it in GitHub Desktop.
Code to enumerate poker hands with two pairs from 5 cards out of a 52 card deck
use std::collections::HashMap;
fn is_two_pairs(c1: u32, c2: u32, c3: u32, c4: u32, c5: u32) -> bool {
let mut hand: HashMap<u32, u32> = HashMap::new();
*hand.entry(c1 % 13).or_insert(0) += 1;
*hand.entry(c2 % 13).or_insert(0) += 1;
*hand.entry(c3 % 13).or_insert(0) += 1;
*hand.entry(c4 % 13).or_insert(0) += 1;
*hand.entry(c5 % 13).or_insert(0) += 1;
if (hand.len() != 3) {
return false;
}
let mut values: Vec<&u32> = hand.values().collect();
values.sort();
return (*values[2] == 2);
}
fn main() {
// A card is a number form 0 to 51.
// Ace of spade = 0; Two if spade = 1; ..... ; King of club = 51.
const DECK: u32 = 13 * 4;
let mut all_hands = 0;
let mut two_pairs = 0;
for i in 0..DECK {
for j in (i..DECK).filter(|x| *x != i) {
for k in (j..DECK).filter(|x| *x != i && *x != j) {
for l in (k..DECK).filter(|x| *x != i && *x != j && *x != k) {
for m in (l..DECK).filter(|x| *x != i && *x != j && *x != k && *x != l) {
// println!("{} {} {} {} {}", i, j, k, l, m);
all_hands += 1;
if is_two_pairs(i, j, k, l, m) {
two_pairs += 1;
}
} // m
} // l
} // k
} // j
} // i
println!("{}", all_hands);
println!("{}", two_pairs);
} // main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment