Skip to content

Instantly share code, notes, and snippets.

@clay-reed-a
Created March 24, 2015 18:56
Show Gist options
  • Save clay-reed-a/a0605076e1e9b3e785a0 to your computer and use it in GitHub Desktop.
Save clay-reed-a/a0605076e1e9b3e785a0 to your computer and use it in GitHub Desktop.
Error in Recursive Routine
"I need to find the set of possible ways of traversing a tree of height n. For a tree of height 4, that looks like this: "
h4 = [
[0, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 0, 1, 2],
[0, 1, 1, 1],
[0, 1, 1, 2],
[0, 1, 2, 2],
[0, 1, 2, 3]
]
"Generally, I can initialize this set of sets, with everything at zero, like so: "
$tree_height = 4
$matrix = []
($tree_height*2).times do |rows|
row = []
$tree_height.times do |columns|
row << 0
end
$matrix << row
end
"My logic is, I can then make this the set of all possible traversals by repeatedly halving the rows, and, then, let's say to the first half, adding one to all columns after and including x, starting at one, and each time increment by one."
h4 = [
[0, 1, 1, 2], # first halving, x = 1
[0, 1, 1, 1],
[0, 1, 2, 3],
[0, 1, 2, 2],
[0, 0, 1, 2], # second halving, x = 2
[0, 0, 1, 1],
[0, 0, 0, 1], # third having, x = 3
[0, 0, 0, 0]
]
"So I need a recursive routine, which I have written as such:"
def add_one_after_x_for_rows x, a, b
(a..b-1).each do |row|
(x+1..$tree_height-1).each do |column|
$matrix[row][column] += 1
end
end
end
def assemble_rows_for_columns_after a, b, x
add_one_after_x_for_rows(x, a, b/2)
if x < $tree_height
assemble_rows_for_columns_after(a,b/2,x+1)
assemble_rows_for_columns_after(b/2,b,x+1)
end
end
assemble_rows_for_columns_after(0,$tree_height*2, 0)
"But this is wrong! Its output looks more like:"
output = [
[0, 1, 2, 3],
[0, 1, 2, 2],
[0, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
"What is the problem with my routine?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment