Last active
August 29, 2015 14:24
-
-
Save jsundram/6786b2fcc326d1289570 to your computer and use it in GitHub Desktop.
You have a cartesian product of a countable number of countable sets and you want to index the elements of that cartesian product. The goal is to find explicit formulas to go either direction in this one-to-one mapping.
This file contains 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
""" | |
Problem -- you have a bounded space defined by the cardinality of each dimension. | |
You want to: | |
a) Go from coordinates inside that space to an index of inside that space (map_point) | |
b) Reverse that (go from an index to a set of coordinates) (unmap_point) | |
""" | |
import operator | |
def get_multipliers(cardinalities): | |
multiplier, multipliers = 1, [] | |
for dimension, cardinality in enumerate(cardinalities): | |
multipliers.append(multiplier) | |
multiplier *= cardinality | |
return multipliers | |
def map_point(X, cardinalities): | |
"""X is an n-dimensional input vector. Find its index in space.""" | |
assert len(X) == len(cardinalities) | |
multipliers = get_multipliers(cardinalities) | |
i = 0 | |
for dimension, value in enumerate(X): | |
i += multipliers[dimension] * value | |
return i | |
def unmap_point(i, cardinalities): | |
"""i is an index in a space defined by cardinalities. Return its coordinates""" | |
X = [] | |
N = reduce(operator.mul, cardinalities, 1) # Max Valid I | |
assert i < N | |
for cardinality in cardinalities: | |
i, value = divmod(i, cardinality) | |
X.append(value) | |
return X | |
def test(): | |
cardinalities = 6, 5 | |
X = (3, 2) | |
i = map_point(X, cardinalities) | |
print(X, cardinalities, i, unmap_point(i, cardinalities)) | |
if __name__ == '__main__': | |
test() |
reiddraper
commented
Jul 15, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment