Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#
# 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}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment