Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created March 14, 2016 07:17
Show Gist options
  • Save ifyouseewendy/de81ba885f7ea46493ce to your computer and use it in GitHub Desktop.
Save ifyouseewendy/de81ba885f7ea46493ce to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
# In Ruby, we can just use Array#flatten
#
# def flatten(array)
# array.flatten
# end
# In case you want a manmade version
def flatten(array)
array.reduce([]) do |res, element|
Array === element ? res += flatten(element) : res << element
end
end
array = [[1,2,[3]],4]
expected = (1..4).to_a
fail "Unequal" unless expected == flatten(array)
array = [[1, 2, [3], [4, 5, [6, 7]]], 8]
expected = (1..8).to_a
fail "Unequal" unless expected == flatten(array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment