owen2345
11/7/2017 - 6:52 PM

array_flatten.rb

# 
# Converts multidimensional array into one-dimensional array
# @param array_data [Array]: Multidimensional array to be converted into one-dimensional array
# @param res [Array]: Internal param control (ignore it)
# @sample 1: flatten([1,2,[3,4]]) => [1,2,3,4]
# @sample 1: flatten([1,2,[3,4], [[5], [6, [7]]]]) => [1,2,3,4]
# @return [Array] Returns a new array that is a one-dimensional
def flatten(array_data, res = [])
  array_data.each{|v| v.is_a?(Array) ? flatten(v, res) : res.push(v) }
  res
end

test1 = [1,2,[3,4]]
test2 = [1,2,[3,4], [[5], [6, [7]]]].flatten
puts "test 1: #{flatten(test1).inspect}"
puts "test 2: #{flatten(test2).inspect}"