gabriele renzi wrote:
This is what I get for posting "simplified" code in the real code
there is no component that is an array or could be interpreded as one
here is the real code.
Note: the bug specifically is why does ModTree::TreeNode::find require
all four args it seems that it should only require aVal same for
Tree:
ump.
A related question is there an easier way to impliment Tree::insert*
TreeNode::find*. It seems the C++ notion of overloaded functions would
be the ideal way.
#!/usr/bin/env ruby
#
# Platform: unspecified
# Author: Aryeh M. Friedman <aryeh@7of9>
# Version of orgin: mudng.0.0.0.1
#
# Copyright (c) 2003. Aryeh M. Friedman and the MudNG Project. All rights
reserved.
# Library for adding generic trees (NOT Hash/Path Trees!!!) to ruby
module ModTree
class TreeException < RuntimeError
end
class TreeNode
attr :nid
attr
arent
attr :level
attr :val
@@tid=0
def initialize(aVal,aParent=nil)
@nid=@@tid
@@tid+=1
@val=aVal
@parent=aParent
if @parent!=nil
@parent.addChild(self)
@
[email protected]+1
else
@level=0
end
@branchs=[]
@cur_branch=0
end
def addChild(aTreeNode)
@branchs.push(aTreeNode)
end
def reset
@cur_branch=0
end
def find(aVal)
walk do |bVal, bLevel, bPid, bId|
aVal==bVal
end
end
def findById(aId)
walk do |aVal,aLevel,aParentId,aNodeId|
aId.to_i==aNodeId.to_i
end
end
def getNext
if @cur_branch>@branchs.length-1
reset
if @parent!=nil
return @parent.getNext
else
return nil
end
end
@cur_branch+=1
return @branchs[@cur_branch-1]
end
def walk
if self.parent!=nil
raise TreeException,"Not root node"
end
node=self
while node!=nil
if node.parent == nil
pid=0
else
pid=node.parent.nid
end
if yield(node.val, node.level, pid, node.nid)==true
tmp=node
while tmp!=nil
tmp.reset
tmp=tmp.parent
end
node.reset
return node
end
node=node.getNext
end
end
end
class Tree
def initialize
@root=TreeNode.new(nil)
end
def walk(&block)
@root.walk(&block)
end
def find(aVal)
@root.find(aVal)
end
def insert(aParent,aVal)
[email protected](aParent)
TreeNode.new(aVal,node)
end
def insertById(aId,aVal)
[email protected](aId)
TreeNode.new(aVal,node)
end
def getParent(aVal)
[email protected](aVal)
if node!=nil then
return node.parent
else
return nil
end
end
def dump
@root.walk {|aVal, aLevel, aParentId, aId| puts "#{'
'.rjust(aLevel)}#{aVal}"}
end
end
end