20 lines
700 B
Rust
20 lines
700 B
Rust
//! Allocation-free enumeration of k-element subsets by bit mask (n <= 8 in practice).
|
|
|
|
use crate::card::Card;
|
|
|
|
/// All masks over `n` positions with exactly `k` bits set.
|
|
pub fn masks(n: usize, k: u32) -> impl Iterator<Item = u32> {
|
|
(0u32..(1u32 << n)).filter(move |m| m.count_ones() == k)
|
|
}
|
|
|
|
/// The cards selected by `mask`, packed into the front of a fixed array.
|
|
pub fn pick<const K: usize>(cards: &[Card], mask: u32) -> Option<[Card; K]> {
|
|
let mut picked = cards.iter().enumerate().filter(|(i, _)| mask >> i & 1 == 1).map(|(_, c)| *c);
|
|
let first = *cards.first()?;
|
|
let mut out = [first; K];
|
|
for slot in out.iter_mut() {
|
|
*slot = picked.next()?;
|
|
}
|
|
Some(out)
|
|
}
|