Last active
March 30, 2016 08:49
-
-
Save stevecj/a24339e6a34baf80755dda8997799319 to your computer and use it in GitHub Desktop.
Coding exercise: Flatten an array in Ruby w/o using `Array#flatten`
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
module ArrayUtils | |
def self.flatten(array, result=[]) | |
array = Array(array) | |
array.each do |entry| | |
case entry | |
when Array | |
flatten entry, result | |
else | |
result << entry | |
end | |
end | |
result | |
end | |
def self.non_recursive_flatten(array) | |
result = [] | |
enum = array.each | |
stack = [] | |
loop do | |
begin | |
entry = enum.next | |
case entry | |
when Array | |
stack << enum | |
enum = entry.each | |
else | |
result << entry | |
end | |
rescue StopIteration | |
enum = stack.pop | |
break unless enum | |
end | |
end | |
result | |
end | |
end | |
p ArrayUtils.flatten( [[1,2,[3]],4] ) | |
# => [1, 2, 3, 4] | |
p ArrayUtils.non_recursive_flatten( [[1,2,[3]],[],4] ) | |
# => [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment