Hello,
Short question:
How to make an iterative method of stack?
Long explanation:
I’m trying to create an iterative method for following structure:
class Obj
attr_accessor: id,: parent_id
def initialize (id, parent_id)
parent_id = @ parent_id
@ id = id
end
def to_s
"id: # {@ id}, parent_id: @ # {parent_id} ’
end
end
left = [Obj.new (1.0), Obj.new (2.1), Obj.new (3.2), Obj.new (4.0),
Obj.new (5.1), Obj new (6.1), Obj.new (7.3)]
My challenge is to make an iterative method, see how far I got:
def menu_iterative (menu)
res = []
el1 = menu.shift
res << el1
while not menu.empty?
res_aux = []
for i in menu
if el1.id == i.parent_id
print el1, “==” i "* ", res_aux.index (el1), “\ n”
res_aux << i
el1 = menu.delete (i)
retry
else
print el1, “! =” i, “\ n”
end
end
res << res_aux unless res_aux.empty?
puts
el1 = menu.shift
res << el1
end
return res
end
puts “result:”
pp menu_iterative (left_it)
I wish the outcome was:
[#<Obj:0x7f35b48cab40 @id=1, @parent_id=0>,
[#<Obj:0x7f35b48cab18 @id=2, @parent_id=1>,
[#<Obj:0x7f35b48caaf0 @id=3, @parent_id=2>,
[#<Obj:0x7f35b48caa50 @id=7, @parent_id=3>]],
[#<Obj:0x7f35b48caaf0 @id=3, @parent_id=2>]],
[#<Obj:0x7f35b48cab18 @id=2, @parent_id=1>,
#<Obj:0x7f35b48caaa0 @id=5, @parent_id=1>,
#<Obj:0x7f35b48caa78 @id=6, @parent_id=1>]]
It seems that the problem is attribution without stack, correct?
I’m attaching all I did.
Thanks for any help.