//! Dealing from a pool that is rearranged in place (private to one simulation run). //! //! The pool is only ever permuted, so any arrangement is a uniform starting point for the next //! partial Fisher-Yates pass; the arrangement itself never leaks out of `monte_carlo`. use crate::card::Card; use crate::rng::Rng; /// Attempts a `Filter` range gets per hand before the last sample is accepted unfiltered. pub const MAX_FILTER_ATTEMPTS: u32 = 200; /// Moves `count` uniformly chosen cards from `pool[front..]` to `pool[front..front + count]`. pub fn shuffle_front(pool: &mut [Card], front: usize, count: usize, rng: Rng) -> Rng { (0..count).fold(rng, |rng, i| { let (offset, rng) = rng.below((pool.len() - front - i) as u64); pool.swap(front + i, front + i + offset as usize); rng }) } /// Deals `count` cards at `front`, re-sampling while `accept` refuses (bounded). /// Fallback: after `MAX_FILTER_ATTEMPTS` refusals the last sample is kept, i.e. a range that /// (almost) never matches degrades to a uniformly random hand instead of failing the run. pub fn deal(pool: &mut [Card], front: usize, count: usize, accept: &dyn Fn(&[Card]) -> bool, rng: Rng) -> Rng { let mut rng = rng; for _ in 0..MAX_FILTER_ATTEMPTS { rng = shuffle_front(pool, front, count, rng); if accept(&pool[front..front + count]) { break; } } rng } /// Deals one of `combos` at `front`: a uniformly chosen hand, re-chosen while one of its /// cards is gone (dead or dealt), bounded by `MAX_FILTER_ATTEMPTS`. Fallback: an empty list, /// or no hand left after the attempts, deals `count` random cards instead. pub fn deal_combo(pool: &mut [Card], front: usize, count: usize, combos: &[Vec], rng: Rng) -> Rng { let mut rng = rng; for _ in 0..if combos.is_empty() { 0 } else { MAX_FILTER_ATTEMPTS } { let (i, next) = rng.below(combos.len() as u64); rng = next; let combo = &combos[i as usize]; let available = combo.len() == count && combo.iter().all(|c| pool[front..].contains(c)); if available { for (k, card) in combo.iter().enumerate() { let at = front + k + pool[front + k..].iter().position(|p| p == card).unwrap_or(0); pool.swap(front + k, at); } return rng; } } shuffle_front(pool, front, count, rng) }