Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting dimension of multidimensional array in ruby

Tags:

arrays

ruby

I just started learning ruby. Now I need to figure out the dimension of a multidimensional array. I had a look at ruby-docs for the all the array methods, but I could not find a method that returns the dimension.

Here is an example:

For [[1, 2],[3,4],[5,6]] the dimension should be 2.

For [[[1,2],[2,3]],[[3,4],[5]]], the dimension should be 3.

like image 631
chappar Avatar asked Mar 03 '12 11:03

chappar


3 Answers

Simple, object-oriented solution.

class Array
  def depth
    map {|element| element.depth + 1 }.max
  end
end

class Object
  def depth
    0
  end
end
like image 98
Reactormonk Avatar answered Sep 21 '22 10:09

Reactormonk


There is not a built-in function for that as there may be multiple definition as to what you mean by "dimension" for an array. Ruby's arrays may contain anything including hashes or other arrays. That's why I believe you need to implement your own function for that.

Asuming that by dimension you mean "the deepest nested level of arrays" this should do the trick:

def get_dimension a
  return 0 if a.class != Array
  result = 1
  a.each do |sub_a|
    if sub_a.class == Array
      dim = get_dimension(sub_a)
      result = dim + 1 if dim + 1 > result
    end
  end
  return result
end

EDIT: and as ruby is a great language and allows you to do some fancy stuff you can also make get_dimension a method of Array:

 class Array
   def get_dimension
   ... # code from above slightly modified
   end
 end
like image 33
Ivaylo Strandjev Avatar answered Sep 20 '22 10:09

Ivaylo Strandjev


in the simplest case

depth = Proc.new do |array|
  depth = 1
  while Array === array.first do
    array = array.first
    depth += 1
  end
  depth
end

array =  [[[1,2],[2,3]],[[3,4],[5]]]    
depth.call(array)
#=> 3

Or this tiny recursive method

def depth(array, depth=1)
  array = array.send(:first)
  Array === array ? depth(array, depth+1) : depth
end

array =  [[[1,2],[2,3]],[[3,4],[5]]]    
depth(array)
#=> 3
like image 23
fl00r Avatar answered Sep 21 '22 10:09

fl00r