Skip to content

Instantly share code, notes, and snippets.

@jsundram
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsundram/6786b2fcc326d1289570 to your computer and use it in GitHub Desktop.
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.
"""
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
Copy link

foldl (\(i, acc) c -> let (i', x) = divMod i c in (i', (x:acc))) (2,[]) [3 :: Int, 4]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment