1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
use crate::{Probability, PROBABILITY_ZERO};
use std::collections::{BTreeMap, HashMap};
use std::fmt::Display;
use std::hash::Hash;
/// A deck of cards.
///
/// This may contain multiple cards which are equal.
///
/// # Example: Uneven dice
///
/// The following code shows how to construct an uneven dice with a second one instead of a six.
///
/// ```
/// use stochasta::CardDeck;
/// use stochasta::Probability;
///
/// let dice = CardDeck::from(vec!["1", "2", "3", "4", "5", "1"]);
///
/// assert_eq!(dice.size(), 6);
/// assert_eq!(dice.probability(&"1"), Probability::new(1, 3));
/// assert_eq!(dice.probability(&"2"), Probability::new(1, 6));
/// assert_eq!(dice.probability(&"5"), Probability::new(1, 6));
/// assert_eq!(dice.probability(&"6"), Probability::new(0, 6));
/// ```
///
/// # Type Parameters
/// - `C`: The type of a single card
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CardDeck<C>
where
C: Eq + Hash + Ord,
{
cards: BTreeMap<C, u64>,
}
impl<C> Display for CardDeck<C>
where
C: Eq + Hash + Ord + Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.cards
.iter()
.map(|(k, v)| format!("{k}: {v}x"))
.collect::<Vec<String>>()
.join("\n")
)
}
}
impl<C> From<Vec<C>> for CardDeck<C>
where
C: Eq + Hash + Ord + Default,
{
fn from(cards: Vec<C>) -> Self {
let mut deck = Self::new();
for card in cards {
deck.add(card);
}
deck
}
}
impl<C> FromIterator<C> for CardDeck<C>
where
C: Eq + Hash + Ord + Default,
{
fn from_iter<T>(cards: T) -> Self
where
T: std::iter::IntoIterator<Item = C>,
{
let mut deck = Self::new();
for card in cards {
deck.add(card);
}
deck
}
}
impl<C> Extend<C> for CardDeck<C>
where
C: Eq + Hash + Ord,
{
fn extend<T: IntoIterator<Item = C>>(&mut self, cards: T) {
for card in cards {
self.add(card);
}
}
}
impl<C> CardDeck<C>
where
C: Eq + Hash + Ord,
{
/// Creates a new empty deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let cards: CardDeck<i32> = CardDeck::new();
/// assert_eq!(cards.is_empty(), true);
/// ```
#[must_use]
pub fn new() -> Self {
Self {
cards: BTreeMap::new(),
}
}
/// Adds the given card once to the deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let card = "demo";
/// let mut deck = CardDeck::new();
/// assert_eq!(deck.count(&card), 0);
///
/// deck.add(card);
/// assert_eq!(deck.count(&card), 1);
/// ```
pub fn add(&mut self, card: C) {
self.add_times(card, 1);
}
/// Adds the card `n` times to the deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let card = "demo";
/// let mut deck = CardDeck::new();
/// assert_eq!(deck.count(&card), 0);
///
/// deck.add_times(card, 5);
/// assert_eq!(deck.count(&card), 5);
/// ```
pub fn add_times(&mut self, card: C, n: u64) {
*self.cards.entry(card).or_insert(0) += n;
}
/// Removes all appearances of the given card from the deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let mut deck = CardDeck::from(vec![1, 3, 3]);
/// assert_eq!(deck.count(&3), 2);
///
/// deck.remove_all(&3);
/// assert_eq!(deck.count(&3), 0);
/// ```
pub fn remove_all(&mut self, card: &C) {
self.cards.remove(card);
}
/// Removes the card `n` times from the deck.
///
/// If `n` is greater than [count](CardDeck::count) the amount will simply set to zero.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let mut deck = CardDeck::from(vec![3, 3, 3]);
/// assert_eq!(deck.count(&3), 3);
///
/// deck.remove_times(3, 2);
/// assert_eq!(deck.count(&3), 1);
/// ```
pub fn remove_times(&mut self, card: C, n: u64) {
let value = self.cards.entry(card).or_insert(0);
if *value >= n {
*value -= n;
} else {
*value = 0;
}
}
/// Sets the amount of `card`s to `n`. Will overwrite any pre-existing value.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let mut deck = CardDeck::new();
/// assert_eq!(deck.count(&"alpha"), 0);
///
/// deck.set_card("alpha", 10);
/// assert_eq!(deck.count(&"alpha"), 10);
/// ```
pub fn set_card(&mut self, card: C, n: u64) {
self.cards.insert(card, n);
}
/// Returns `true`, if the deck is empty.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let cards: CardDeck<i32> = CardDeck::new();
/// // ...
/// assert_eq!(cards.is_empty(), cards.size() == 0);
/// ```
#[must_use]
pub fn is_empty(&self) -> bool {
self.cards.is_empty()
}
/// Returns the number of cards in the deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let weird_dice = CardDeck::from(vec![1, 2, 1]);
/// assert_eq!(weird_dice.size(), 3);
/// ```
#[must_use]
pub fn size(&self) -> u64 {
self.cards.iter().map(|x| x.1).sum()
}
/// Returns the probability of an equal card to be drawn.
///
/// # Example
///
/// ```
/// use stochasta::Probability;
/// use stochasta::CardDeck;
///
/// let dice = CardDeck::from(vec!["1", "2", "3", "4", "5", "6"]);
/// assert_eq!(dice.probability(&"1"), Probability::new(1, 6));
/// ```
#[must_use]
pub fn probability(&self, card: &C) -> Probability {
self.cards.get(card).map_or_else(
|| PROBABILITY_ZERO,
|count| Probability::new(*count, self.size()),
)
}
/// Returns the probability of the cards to be drawn.
///
/// The probabilities are guaranteed to be `> 0`.
///
/// # Example
///
/// ```
/// use std::collections::HashMap;
/// use stochasta::Probability;
/// use stochasta::CardDeck;
///
/// let coin = CardDeck::from(vec!["heads", "tails"]);
/// assert_eq!(
/// coin.probabilities(),
/// HashMap::from([
/// (&"heads", Probability::new(1, 2)),
/// (&"tails", Probability::new(1, 2)),
/// ])
/// );
/// ```
#[must_use]
pub fn probabilities(&self) -> HashMap<&C, Probability> {
let size = self.size();
self.cards
.iter()
.filter(|(_, &count)| count > 0)
.map(|(card, &count)| (card, Probability::new(count, size)))
.collect()
}
/// Checks whether the card is contained at least once in the deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let card = "demo";
/// let mut deck = CardDeck::new();
/// assert_eq!(deck.contains(&card), false);
///
/// deck.add(card);
/// assert_eq!(deck.contains(&card), true);
/// ```
#[must_use]
pub fn contains(&self, card: &C) -> bool {
self.count(card) > 0
}
/// Checks the amount of equal cards.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let deck = CardDeck::from(vec![1, 3, 3]);
///
/// assert_eq!(deck.count(&1), 1);
/// assert_eq!(deck.count(&3), 2);
/// assert_eq!(deck.count(&5), 0);
/// ```
#[must_use]
pub fn count(&self, card: &C) -> u64 {
self.cards.get(card).copied().unwrap_or_default()
}
}
impl<C> CardDeck<C>
where
C: Eq + Hash + Ord + Clone,
{
/// Draws one exemplar of `card` from the deck and returns a **new** deck.
///
/// # Example
///
/// ```
/// use stochasta::CardDeck;
///
/// let original = CardDeck::from(vec![1, 2, 3]);
///
/// assert_eq!(original.contains(&3), true);
///
/// let new_deck = original.draw(3);
///
/// assert_eq!(original.contains(&3), true);
/// assert_eq!(new_deck.contains(&3), false);
/// ```
#[must_use]
pub fn draw(&self, card: C) -> Self {
let mut deck = (*self).clone();
deck.remove_times(card, 1);
deck
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn probabilities_no_zero_returns() {
let mut deck = CardDeck::from(vec![1, 2, 3]);
deck.remove_times(3, 1);
assert!(deck.probabilities().values().all(|&x| x > PROBABILITY_ZERO));
}
#[test]
fn to_string() {
let deck = CardDeck::from(vec![3, 1, 2, 3]);
assert_eq!("1: 1x\n2: 1x\n3: 2x", deck.to_string());
}
}