Created
July 16, 2016 03:55
-
-
Save abhinavmsra/a537b5cd7f76106ae5656c94b27c2f20 to your computer and use it in GitHub Desktop.
Flattens an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains 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
# Flattens an array of arbitrarily nested arrays of integers into a flat array of integers | |
# | |
# Algorithm: | |
# 1. Iterate over each element in the array. | |
# 2. If the element contains nested array elements, apply the same function recursively to each elements. | |
# 3. For integer values, push them into a flat array | |
# | |
# @param array[Array], nested array to be flattened | |
# @return [Array], flattened array | |
def flatten(array) | |
array.reduce([]) do |acc, elem| | |
Array === element ? acc += flatten(elem) : acc << elem | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment