Jesús Gabriel y Galán
11/22/2007 4:49:00 PM
On Nov 22, 2007 3:03 PM, Jes=FAs Gabriel y Gal=E1n <jgabrielygalan@gmail.co=
m> wrote:
> On Nov 22, 2007 10:28 AM, Chris Morales <primo.tertio@gmail.com> wrote:
> > p [2,3,3,5,4,4].depthen =3D> [2,[3,3,[[5],4,4]]]
> >
> > I will be really thankful if anybody could help me improve this monster
> > with nice ruby tricks.
>
>
> With your code:
>
> [2,3,5,3].depthen # =3D> [2, [3, [[5], 3]]]
>
> Shouldn't this be:
>
> [2, [3, [[5]], 3]]
>
> ?
>
> I'm trying to think of an elegant solution, but I'm kind of slow today...
I managed to get some time at work and this is my first try,
I use a stack to maintain the arrays for each level when you are
going upwards, so you can add to the same array when you go
downwards (makes any sense?):
class Array
def depthen
depth =3D self[0]
result =3D []
stack =3D []
current =3D result
each do |x|
case depth <=3D> x
when 0
current << x
when -1
diff =3D x - depth
value =3D [x]
tmp =3D value
(diff - 1).times do
value =3D [value]
stack.push value
end
current << value
current =3D tmp
stack.push current
when 1
diff =3D depth - x + 1
diff.times {current =3D stack.pop}
current =3D result if current.nil?
current << x
end
depth =3D x
end
result
end
end
a =3D [[2,3,3,4,5,4,4], [2,3,5,3, 2]]
a.each {|x| p x.depthen}
[2, [3, 3, [4, [5], 4, 4]]]
[2, [3, [[5]], 3], 2]
Have fun,
Jesus.