Implements a method that flattens a nested array, based on recursion.
Includes several tests that check the method behavior with different arrays.
Last active
June 15, 2016 04:21
-
-
Save juandefelix/b3418635d6a4a724791f753970c25849 to your computer and use it in GitHub Desktop.
Implements a method that flattens a nested array, based on recursion.
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
# Flattens an array of arbitrarily nested arrays of integers into a flat array of integers. | |
# e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
def my_flatten(ary, flattened_array=[]) | |
return flattened_array if ary.empty? | |
case ary[0] | |
when Fixnum, Integer | |
flattened_array.push(ary[0]) | |
when Array | |
flattened_array = my_flatten(ary[0], flattened_array) | |
end | |
return my_flatten(ary[1..-1], flattened_array) | |
end | |
my_flatten([1,2,3,[4,5]]) |
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
require File.expand_path('../../lib/my_flatten.rb', __FILE__) | |
describe "my_flatten" do | |
it 'should return an array' do | |
expect(my_flatten([1])).to be_an Array | |
end | |
describe 'should return an flattened array' do | |
it 'when passing a nested array' do | |
expect(my_flatten([1, [2, 3]])).to eq [1, 2, 3] | |
end | |
it 'when passing a more complex array' do | |
expect(my_flatten([1, [2, 3], [4, 5]])).to eq [1, 2, 3, 4, 5] | |
end | |
it 'when passing other complex nested arrays' do | |
expect(my_flatten([1, [2, 3, [4, 5], 6, 7]])).to eq [1, 2, 3, 4, 5, 6, 7] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment