Last active
March 26, 2016 14:58
-
-
Save LLBlumire/89e9f295ca811a21a418 to your computer and use it in GitHub Desktop.
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
extern crate rand; | |
use std::collections::HashMap; | |
use rand::thread_rng; | |
use rand::Rng; | |
type Card = (Suit, i32); | |
use Suit::*; | |
fn main() { | |
// New source for random numbers | |
let mut rng = thread_rng(); | |
// Total number of simulations run | |
let mut total = 0.0; | |
// Number of simulations where all four cards are valid | |
let mut positive = 0.0; | |
// Simulation Loop | |
loop { | |
// Create a new deck of cards | |
let deck: Vec<Card> = new_deck(&mut rng); | |
// Deal those cards to 4 players | |
let mut players = deal_to_players(4, deck, &mut rng); | |
// Assume that the predicate is not true | |
let mut matching: HashMap<Suit, bool> = HashMap::new(); | |
for suit in [Heart, Diamond, Spade, Club].iter().cloned() { | |
matching.insert(suit, false); | |
} | |
// For every suit in every players hand | |
for player in players { | |
for suit in [Heart, Diamond, Spade, Club].iter().cloned() { | |
// If they hold both the ace and king | |
if player.contains(&(suit, 1)) && player.contains(&(suit, 13)) { | |
// Set that suit's value in our predicate map to true | |
*matching.get_mut(&suit).unwrap() = true; | |
} | |
} | |
} | |
// Incrememnt the number of simulations | |
total += 1.0; | |
// If all suits meet our predicate condition | |
if matching.values().fold(true, |i, acc| i & acc) { | |
// Increment the number of positive simulations | |
positive += 1.0; | |
} | |
// Output the simulation result | |
println!("{}% of {}", (positive*100.0) / total, total); | |
} | |
} | |
fn deal_to_players<R: Rng>(q: usize, deck: Vec<Card>, rng: &mut R) -> Vec<Vec<Card>> { | |
let mut players: Vec<Vec<Card>> = Vec::new(); | |
for i in 0..q { | |
players.push(Vec::new()); | |
for _ in 0..deck.len().clone() { | |
players[i].push(*rng.choose(&deck[..]).unwrap()); | |
} | |
} | |
players | |
} | |
fn new_deck<R: Rng>(rng: &mut R) -> Vec<Card> { | |
let mut deck = Vec::new(); | |
for i in 1..14 { | |
for suit in [Heart, Diamond, Spade, Club].iter().cloned() { | |
deck.push((suit, i)); | |
} | |
} | |
rng.shuffle(&mut deck[..]); | |
deck | |
} | |
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] | |
enum Suit { | |
Heart, | |
Diamond, | |
Spade, | |
Club | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment