BitSet
import "std/collections" (included in import "std") · namespace std.collections
A BitSet is a set of non-negative integers stored as bits, 64 per machine word. It is very compact and fast for dense sets of small numbers: flags, seen-IDs, sieves. It grows to fit the largest bit you set.
grav
import "std"
fn main() {
let primes = new BitSet()
for (n in 2..50) { primes.set(n) }
for (n in 2..8) {
for (m in (n * n)..50 step n) { primes.unset(m) }
}
print(primes.count())
print(primes.get(47))
print(primes)
let small = new BitSet()
for (n in 0..10) { small.set(n) }
small.intersectWith(primes)
print(small.toArray())
}15
true
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47}
[2, 3, 5, 7]Setting a negative bit throws IndexError.
API
class BitSet
Constructors
new BitSet()
Methods
fn set(bit: int)— Turns bitbiton (IndexError when negative).fn unset(bit: int)— Turns bitbitoff.fn flip(bit: int)— Turns bitbiton if it was off, and off if it was on.fn get(bit: int) -> bool— Whether bitbitis on.fn contains(bit: int) -> bool— Whether bitbitis on (same as get).fn count() -> int— Number of set bits.fn size() -> int— The number of bits that are on (same as count()).fn isEmpty() -> bool— Whether no bit is on.fn clear()— Turns every bit off.fn unionWith(other: BitSet)— In-place set algebra.fn intersectWith(other: BitSet)— Keeps only the bits that are also on inother.fn toString() -> string— Set bits in increasing order. As text: {1, 2, 3} (strings in quotes).fn toArray() -> Array<int>— The numbers of the bits that are on, in increasing order.