Created
September 9, 2015 19:27
-
-
Save arikrak/23bd192a82a870e3c1ef to your computer and use it in GitHub Desktop.
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 into a flat array | |
def flatten(ar) | |
flat_ar = [] | |
ar.each do |elem| | |
if elem.class == Array | |
flat_ar.concat flatten(elem) | |
else | |
flat_ar << elem | |
end | |
end | |
return flat_ar | |
end | |
# simple 'test cases' | |
p [] == flatten([]) | |
p [1] == flatten([1]) | |
p [1] == flatten([[[1]]]) | |
p [1,2] == flatten([[1],[2]]) | |
p [1,2,3,4] == flatten([1,[2],[3,[4]]]) | |
p [1,2,3,4] == flatten([[[1],2],3,4]) | |
p [1,2,3,4,5,6,7,8,9,10] == flatten([1,2,[3,4],5,[6,[7,8,[9,10]]]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment