Created
November 7, 2017 18:52
-
-
Save owen2345/d5cc5c1b1a288499488518b5a45fcf75 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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