Skip to content

Instantly share code, notes, and snippets.

@william-silversmith
Last active February 18, 2018 04:06
Show Gist options
  • Save william-silversmith/a414a14ec72692c6d27024f9cb477d9f to your computer and use it in GitHub Desktop.
Save william-silversmith/a414a14ec72692c6d27024f9cb477d9f to your computer and use it in GitHub Desktop.
COUNTLESS3D + Zero Correction + Dynamic Programming
from itertools import combinations
from functools import reduce
import numpy as np
def dynamic_zero_corrected_countless3d(data):
sections = []
# shift zeros up one so they don't interfere with bitwise operators
# we'll shift down at the end
data += 1
# This loop splits the 2D array apart into four arrays that are
# all the result of striding by 2 and offset by (0,0), (0,1), (1,0),
# and (1,1) representing the A, B, C, and D positions from Figure 1.
factor = (2,2,2)
for offset in np.ndindex(factor):
part = data[tuple(np.s_[o::f] for o, f in zip(offset, factor))]
sections.append(part)
pick = lambda a,b: a * (a == b)
lor = lambda x,y: x + (x == 0) * y # logical or
subproblems2 = {}
results2 = None
for x,y in combinations(range(7), 2):
res = pick(sections[x], sections[y])
subproblems2[(x,y)] = res
if results2 is not None:
results2 = lor(results2, res)
else:
results2 = res
subproblems3 = {}
results3 = None
for x,y,z in combinations(range(8), 3):
res = pick(subproblems2[(x,y)], sections[z])
# 7 is the terminal element, we don't need to memoize these solutions
if z != 7:
subproblems3[(x,y,z)] = res
if results3 is not None:
results3 = lor(results3, res)
else:
results3 = res
results4 = ( pick(subproblems3[(x,y,z)], sections[w]) for x,y,z,w in combinations(range(8), 4) )
results4 = reduce(lor, results4)
final_result = reduce(lor, (results4, results3, results2, sections[-1])) - 1
data -= 1
return final_result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment