Created
June 23, 2013 01:26
-
-
Save HoyaBoya/5843354 to your computer and use it in GitHub Desktop.
This is the answer to an old interview question I used to ask.
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
class ArrayFlattener | |
# simple recursive flatten | |
def flatten(a) | |
new_a = [] | |
a.each do |i| | |
if i.instance_of?(Array) | |
new_a.concat(flatten(i)) | |
else | |
new_a << i | |
end | |
end | |
new_a | |
end | |
# slightly less simple non-recursive flatten | |
def flatten_non_recursive(a) | |
new_a = [] | |
# keep spinning while array not empty | |
while !a.empty? | |
# array element | |
if a.first.instance_of?(Array) | |
# remove the element and place each element at front and resume from the new start | |
a.shift.each_with_index do |element, j| | |
a.insert(j, element) | |
end | |
# non-array element, remove and place into new array | |
else | |
new_a << a.shift | |
end | |
end | |
new_a | |
end | |
end | |
require "test/unit" | |
class ArrayFlattenerTest < Test::Unit::TestCase | |
def test_flatten_simple_case | |
a = [1, 2, 3, 4] | |
a2 = ArrayFlattener.new.flatten(a) | |
assert_equal [1, 2, 3, 4], a2 | |
end | |
def test_flatten_complex_case | |
a = [1, 2, [3, [4]]] | |
a2 = ArrayFlattener.new.flatten(a) | |
assert_equal [1, 2, 3, 4], a2 | |
end | |
def test_flatten_non_recursive_simple_case | |
a = [1, 2, 3, 4] | |
a2 = ArrayFlattener.new.flatten_non_recursive(a) | |
assert_equal [1, 2, 3, 4], a2 | |
end | |
def test_flatten_non_recursive_complex_case | |
a = [1, 2, [3, [4]]] | |
a2 = ArrayFlattener.new.flatten_non_recursive(a) | |
assert_equal [1, 2, 3, 4], a2 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment