I created a data structure to compactly represent an array of small integers:
/*
* Compactly represents an array of N unsigned integers, where each one only
* requires B bits to store.
*/
template<uint32_t N, uint8_t B>
class __attribute__((packed)) small_int_array {
private:
static const uint32_t items_per_page = 64 / B;
static const uint32_t num_pages = (N + items_per_page - 1) / items_per_page;
static const uint64_t mask_unit = (1UL << B) - 1;
struct helper_t {
uint32_t page;
uint8_t offset;
helper_t(uint32_t index) : page(index/items_per_page),
offset(index%items_per_page) {}
};
uint64_t _pages[num_pages];
public:
small_int_array() { memset(this, 0, sizeof(this)); }
uint8_t get(uint32_t index) const {
helper_t helper(index);
uint8_t shift = B*helper.offset;
return (_pages[helper.page] & (mask_unit << shift)) >> shift;
}
void set(uint32_t index, uint8_t value) {
helper_t helper(index);
uint8_t shift = B*helper.offset;
_pages[helper.page] &= ~0UL - (mask_unit << shift);
_pages[helper.page] |= ((uint64_t)value) << shift;
}
};
I then implemented this special method:
/*
* Returns a uniformly random index such that get(index)==value.
* Returns -1 if no such index exists.
*/
int32_t get_random_index(uint8_t value) const {
int32_t candidates[N];
int size=0;
uint32_t index = 0;
for (int i=0; i<num_pages; ++i) {
uint64_t page = _pages[i];
for (int j=0; j<items_per_page; ++j) {
candidates[size] = index++;
if (index==N) break;
bool match = (page & mask_unit) == value;
size += match ? 1 : 0;
page = page >> B;
}
}
if (size==0) return -1;
return candidates[rand() % size];
}
This does what I want, but I'm wondering if there is a more efficient implementation using bit tricks in lieu of the second for-loop. I'm open to changing the bit representation of the object as long as its size doesn't increase.
I'm using N~=100 and B<=4.