Created
September 9, 2015 01:12
-
-
Save lpereira/9d95ee6caeacdaade299 to your computer and use it in GitHub Desktop.
Value packing with prime numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import math | |
def pack_bits(*bits): | |
n = 0 | |
max_n = 1 | |
for value, prime_for_value in bits: | |
while n % prime_for_value != value: | |
n += max_n | |
max_n *= prime_for_value | |
return n | |
def test(*values): | |
packed = pack_bits(*values) | |
bits = math.ceil(math.log(packed, 2)) or 1 | |
print("Values: %s, packed: %d (%d bits)" % (values, packed, bits)) | |
for value, prime in values: | |
assert(packed % prime == value) | |
if __name__ == '__main__': | |
test((1, 3), (4, 5), (3, 7)) | |
test((2, 3), (4, 5), (3, 7)) | |
test((2, 3), (4, 5), (6, 7)) | |
test((2, 3), (1, 5), (3, 7)) | |
test((2, 3), (2, 5), (3, 7)) | |
test((2, 3), (3, 5), (3, 7)) | |
test((2, 3), (4, 5), (3, 7)) | |
test((2, 3), (4, 5), (4, 7)) | |
test((2, 3), (4, 5), (5, 7)) | |
test((2, 3), (4, 5), (6, 7)) | |
test((1, 3), (1, 5), (1, 7)) | |
test((0, 3), (1, 5), (0, 7)) | |
test((1, 3), (2, 5), (3, 7), (10, 13)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment