AI 24/25 Project Software
Documentation for the AI 24/25 course programming project software
Loading...
Searching...
No Matches
int_packer.h
1#ifndef ALGORITHMS_INT_PACKER_H
2#define ALGORITHMS_INT_PACKER_H
3
4#include <vector>
5
6/*
7 Utility class to pack lots of unsigned integers (called "variables"
8 in the code below) with a small domain {0, ..., range - 1}
9 tightly into memory. This works like a bitfield except that the
10 fields and sizes don't need to be known at compile time.
11
12 For example, if we have 40 binary variables and 20 variables with
13 range 4, storing them would theoretically require at least 80 bits,
14 and this class would pack them into 12 bytes (three 4-byte "bins").
15
16 Uses a greedy bin-packing strategy to pack the variables, which
17 should be close to optimal in most cases. (See code comments for
18 details.)
19*/
20namespace int_packer {
21class IntPacker {
22 class VariableInfo;
23
24 std::vector<VariableInfo> var_infos;
25 int num_bins;
26
27 int pack_one_bin(const std::vector<int> &ranges,
28 std::vector<std::vector<int>> &bits_to_vars);
29 void pack_bins(const std::vector<int> &ranges);
30public:
31 typedef unsigned int Bin;
32
33 /*
34 The constructor takes the range for each variable. The domain of
35 variable i is {0, ..., ranges[i] - 1}. Because we are using signed
36 ints for the ranges (and genenerally for the values of variables),
37 a variable can take up at most 31 bits if int is 32-bit.
38 */
39 explicit IntPacker(const std::vector<int> &ranges);
40 ~IntPacker();
41
42 int get(const Bin *buffer, int var) const;
43 void set(Bin *buffer, int var, int value) const;
44
45 int get_num_bins() const { return num_bins; }
46};
47}
48
49#endif