Created
March 14, 2016 07:17
-
-
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].
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
# 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