Created
February 5, 2024 23:01
-
-
Save fancellu/5c309ee74b7d3dc5c2b11c9f7a514691 to your computer and use it in GitHub Desktop.
Rust application to total up a hand of cards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use lazy_static::lazy_static; | |
use std::collections::HashMap; | |
// Ace is worth 11, except if total >21, then it is equal to 1 | |
#[derive(Debug, PartialEq, Eq, Hash)] | |
enum Card { | |
SmallAce, | |
Ace, | |
Two, | |
Three, | |
Four, | |
Five, | |
Six, | |
Seven, | |
Eight, | |
Nine, | |
Ten, | |
Jack, | |
Queen, | |
King, | |
} | |
lazy_static! { | |
static ref CARD_VALUES: HashMap<Card, usize> = { | |
let mut map = HashMap::new(); | |
map.insert(Card::SmallAce, 1); | |
map.insert(Card::Ace, 11); | |
map.insert(Card::Two, 2); | |
map.insert(Card::Three, 3); | |
map.insert(Card::Four, 4); | |
map.insert(Card::Five, 5); | |
map.insert(Card::Six, 6); | |
map.insert(Card::Seven, 7); | |
map.insert(Card::Eight, 8); | |
map.insert(Card::Nine, 9); | |
map.insert(Card::Ten, 10); | |
map.insert(Card::Jack, 10); | |
map.insert(Card::Queen, 10); | |
map.insert(Card::King, 10); | |
map | |
}; | |
} | |
fn card_value(card: &Card) -> usize { | |
*CARD_VALUES.get(card).unwrap_or(&0) // Return 0 for unknown cards | |
} | |
struct Hand { | |
cards: Vec<Card>, | |
} | |
impl Hand { | |
fn value(mut self) -> usize { | |
loop { | |
let total = self.cards.iter().map(|card| card_value(card)).sum(); | |
if total <= 21 { | |
return total; | |
} | |
if let Some(index) = self.cards.iter().position(|card| *card == Card::Ace) { | |
self.cards[index] = Card::SmallAce; | |
} else { | |
return total; | |
} | |
} | |
} | |
} | |
fn main() { | |
let hand = Hand { | |
cards: vec![Card::Ace, Card::King], | |
}; | |
println!("{}", hand.value()); | |
let hand = Hand { | |
cards: vec![Card::Ace, Card::King, Card::Ace], | |
}; | |
println!("{}", hand.value()); | |
let hand = Hand { | |
cards: vec![Card::Ace, Card::Two, Card::Ace], | |
}; | |
println!("{}", hand.value()); | |
let hand = Hand { cards: vec![] }; | |
println!("{}", hand.value()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
21 | |
12 | |
14 | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment