I try to implement Algorithm O (Oriented forests) from Donald E. Knuth: 'The Art of Computer Programming - Volume 4, Fascile 4, Generating All Trees' on page 24.
My Python solution is:
def generate_oriented_forest(n):
"""Algorithm O from Knuth TAoCP, Fascicle 4, p. 25. """
p = range(-1, n)
while True:
yield p[1:]
if p[n] > 0: p[n] = p[p[n]]
else:
k_largest = 0
for k in range(1,n):
if p[k] != 0: k_largest = k
k = k_largest
if k == 0: return
j = p[k]
d = k-j
if p[k-d] == p[j]: p[k] = p[j]
else: p[k] = p[k-d] + d
while k != n:
#print k, p
k = k+1
if p[k-d] == p[j]: p[k] = p[j]
else: p[k] = p[k-d] + d
if __name__ == "__main__":
for el in generate_oriented_forest(4):
print el
# According to page 23 and also Table 1 p.4 I would expect the sequence:
# 0123, 0122, 0121, 0120, 0111, 0110, 0101, 0100, 0000
My Implementation gives me:
[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], [0, 1, 1, 1], [0, 1, 1, 0],
[0, 1, 0, 3],
[0, 1, 0, 0], [0, 0, 0, 0].
I'm already looking too long for a bug. Hope someone can point me in the right direction of fix my code. Is my understanding of the algorithm correct? Any improvements on my python style are also appreciated. Thanks for your help.
I digged up the original articel: SIAM Journal of Computing, T. Beyer and S.M. Hedetniemi, 'Constant Time generation of rooted trees". The paper explains the algorithm really well. Here's my implementation:
It gives me the expected result. But I'm still wondering why Knuth's algorithm doesn't work. Would be cool to find out.