Skip to content

Instantly share code, notes, and snippets.

@abhinavmsra
Created July 16, 2016 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhinavmsra/a537b5cd7f76106ae5656c94b27c2f20 to your computer and use it in GitHub Desktop.
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
# 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