Created
July 12, 2016 05:36
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
def flatten src_array | |
flat = [] | |
# It would be more readable to just call flat.concat(flatten(...)) recurisvely | |
# but that creates and destroys a lot of intermediate arrays, which may be costly | |
append_all(flat, src_array) | |
flat | |
end | |
def append_all dest_array, src_array | |
src_array.each do |value| | |
if value.kind_of?(Array) | |
append_all(dest_array, value) | |
else | |
dest_array << value | |
end | |
end | |
end | |
# Ordinarily I'd add some tests here, but as I don't even know if I meet the | |
# requirements for this job, I think I've spent enough time on this. | |
# | |
# flatten([1,2,[3,[4,5]],[6,7]]) | |
# => [1, 2, 3, 4, 5, 6, 7] | |
# flatten([[1,2,[3]],4]) | |
# => [1, 2, 3, 4] | |
# flatten([[1,2,[3,5,[8,9]]],4]) | |
# => [1, 2, 3, 5, 8, 9, 4] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment