I’m looking to improve my skills as a Rubyist and would like to know if
the
“depth” method could be expressed more precisely. Any help would be
greatly
appreciated, thanks!

require ‘test/unit’

class Node
attr_accessor :value, :lchild, :rchild

def depth
[lchild ? lchild.depth : 0, rchild ? rchild.depth : 0].max + 1
end
end

class NodeTest < Test::Unit::TestCase
def setup @n = Node.new
end

def test_depth_of_one @n.lchild = Node.new @n.lchild.lchild = Node.new @n.rchild = Node.new
assert @n.depth == 1, “depth of node should be one, was #{@n.depth}”
end

def test_depth_of_two @n.lchild = Node.new @n.rchild = Node.new
assert @n.lchild.depth == 1, “depth of lchild should be one”
assert @n.rchild.depth == 1, “depth of rchild should be one”
assert @n.depth == 2, “depth of tree should be two, was #{@n.depth}”
end
end

Oops … I see that my test case was incorrect. It should’ve been:

def test_depth_of_one @n.lchild = Node.new @n.lchild.lchild = Node.new @n.rchild = Node.new
assert @n.depth == 3, “depth of node should be one, was #{@n.depth}”
end

On Tue, May 3, 2011 at 6:28 AM, Christopher D. [email protected]
wrote:

attr_accessor :value, :lchild, :rchild

def depth
[lchild ? lchild.depth : 0, rchild ? rchild.depth : 0].max + 1
end
end

def depth
1 + [lchild,rchild].map {|ch| [ch}.max
end

Does not work: apart from the syntax invocation of #depth is missing.
If we add that we have a solution that has been proposed already.

or even:

def depth
1 + [lchild,rchild].map(&:to_i).max
end

alias to_i depth

Now that’s an interesting idea to use the knowledge that nil.to_i => 0!

empty? ? 0 : [lchild,rchild].map(&:depth).max
end

I don’t think this captures the original semantics properly. Now
there are only two states: empty, not empty. But the original design
allowed for more states: empty, left set, right set, both set. Even
if not for #depth this is likely important for other tree algorithms.

Does not work: apart from the syntax invocation of #depth is missing.
If we add that we have a solution that has been proposed already.

Uh, yeah. I messed something up in editing that. I’m not entirely sure
what it was supposed to be.

empty? ? 0 : [lchild,rchild].map(&:depth).max
end

I don’t think this captures the original semantics properly. Now
there are only two states: empty, not empty. But the original design
allowed for more states: empty, left set, right set, both set. Even
if not for #depth this is likely important for other tree algorithms.

Yeah, it depends on things in the code we can’t see; most of the tree
implementations I’ve seen either use nil pointers for children and
populate them with real nodes when they get data for them, or use
empty nodes for children only of populated nodes and then populate the
empty nodes when data arrives for them, but its possible that this one
needs more differentiation.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.