From: "Jesús Gabriel y Galán" Date: 2007-11-23T01:48:35+09:00 Subject: Re: How to give depth to arrays? On Nov 22, 2007 3:03 PM, Jesús Gabriel y Galán wrote: > On Nov 22, 2007 10:28 AM, Chris Morales wrote: > > p [2,3,3,5,4,4].depthen => [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 # => [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 = self[0] result = [] stack = [] current = result each do |x| case depth <=> x when 0 current << x when -1 diff = x - depth value = [x] tmp = value (diff - 1).times do value = [value] stack.push value end current << value current = tmp stack.push current when 1 diff = depth - x + 1 diff.times {current = stack.pop} current = result if current.nil? current << x end depth = x end result end end a = [[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.