Expand description
This is a small dependency-free crate to enumerate all bit combinations less than given unsigned integer value
keeping 1s in the bits.
use bit_combi_iter::BitCombinations;
let mut c = BitCombinations::new(0b00010100u8);
// Iterates all bit combinations less than 0b10100
assert_eq!(c.next().unwrap(), 0b00010010);
assert_eq!(c.next().unwrap(), 0b00010001);
assert_eq!(c.next().unwrap(), 0b00001100);
assert_eq!(c.next().unwrap(), 0b00001010);
assert_eq!(c.next().unwrap(), 0b00001001);
assert_eq!(c.next().unwrap(), 0b00000110);
assert_eq!(c.next().unwrap(), 0b00000101);
assert_eq!(c.next().unwrap(), 0b00000011);
// After iterating all combinations, the iterator reaches the end
assert!(c.next().is_none());This crate is useful when you want to enumerate all n bit integers including k ones.
// Enumerate all 5 bit integers including 3 ones (as u8)
let mut c = BitCombinations::new(0b11100u8);
assert_eq!(c.next().unwrap(), 0b11010);
assert_eq!(c.next().unwrap(), 0b11001);
assert_eq!(c.next().unwrap(), 0b10110);
assert_eq!(c.next().unwrap(), 0b10101);
assert_eq!(c.next().unwrap(), 0b10011);
assert_eq!(c.next().unwrap(), 0b01110);
// ...The algorithm was borrowed from the blog post by @herumi.
Structs§
- BitCombinations
- An iterator to iterate all bit combinations less than given unsigned integer value keeping
1s in the bits. TheUtype parameter can beu8,u16,u32,u64oru128primitive types. Size of this struct is exactly the same as size ofU.