Run-Length and Bit-Packing Codec
DatabricksOnsiteHard
Build Codec, a small compression scheme for streams of unsigned integers. The constructor takes bit_width; every value in a stream is in [0, 2^bit_width - 1]. A compressed stream is a list of block strings of two kinds:
RLE:<value>:<count>stands forcountcopies ofvalue.BP:<count>:<bits>stands forcountvalues written one after another, each as exactlybit_widthbinary digits with leading zeros, sobitshascount * bit_widthdigits.
Each test drives one Codec(bit_width) instance through a sequence of calls and checks every return value.
Part 1: Encode
Implement encode(values), which takes a list of non-negative integers and returns the list of block strings for that stream.
Every maximal run of 8 or more equal values becomes one RLE block holding the value and the full run length. The values between runs (and before the first or after the last run) are packed: each stretch of such values, read left to right, is cut into groups of 8, and each group becomes one BP block. Only the last group of a stretch may hold fewer than 8 values. Runs shorter than 8 are part of the stretch they sit in. Blocks appear in stream order, and an empty values gives an empty list.
- Example 1
- init
[2]- operations
[["encode",[[3,3,3,3,3,3,3,3,1,2,3]]],["encode",[[1,2,1,2,1,2,1,2,3,3,3,3,3,3,3,3,0]]],["encode",[[1,1,1,1,1,1,1]]]]- Output
[["RLE:3:8","BP:3:011011"],["BP:8:0110011001100110","RLE:3:8","BP:1:00"],["BP:7:01010101010101"]]
Why: Eight 3s in a row form a maximal run, so they become
RLE:3:8; the remaining 1, 2, 3 are packed two bits each as 01 10 11. In the second stream the first eight values fill one packed block, the eight 3s are a run, and the final 0 is a packed block of one. Seven equal values are below the run threshold, so they stay packed as seven copies of 01.
Constraints
1 <= bit_width <= 160 <= values[i] < 2^bit_width0 <= len(values) <= 10^41 <= len(operations) <= 10