Skip to content

Instantly share code, notes, and snippets.

@amaranth
Last active January 22, 2016 04:41
Show Gist options
  • Save amaranth/a9ed8fff9a3c029aa743 to your computer and use it in GitHub Desktop.
Save amaranth/a9ed8fff9a3c029aa743 to your computer and use it in GitHub Desktop.
# cartesian product is 3^N
# all that have one or no zeros is 2^(N - 1) * (N + 2)
# all that have no zeros is 2^N
# all that have one zero is 2^(N - 1) * N
# index less than nonZero has no zeros, simple bitmask and shift to interpret bits as -1 or 1
# rest do that for N-1 fields then insert a zero
def gradient_helper(index, dimensions):
result = []
for i in range(0, dimensions):
if index & 0x1:
result.append(-1)
else:
result.append(1)
index >>= 1
return result
def gradient(index, dimensions):
total = 2**(dimensions - 1) * (dimensions + 2)
nonZero = 2**dimensions
index = index % total
if index < nonZero:
return gradient_helper(index, dimensions)
index = index - nonZero
zeroAt = index % dimensions
index = index / dimensions
temp = gradient_helper(index, dimensions - 1)
result = []
i = 0
j = 0
while i < dimensions:
if i == zeroAt:
result.append(0)
i += 1
continue
result.append(temp[j])
i += 1
j += 1
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment