Skip to content

Instantly share code, notes, and snippets.

@AfolabiOlaoluwa
Last active September 17, 2019 21:37
Show Gist options
  • Save AfolabiOlaoluwa/e56ad1b5478dc96a8c45232d8c37956b to your computer and use it in GitHub Desktop.
Save AfolabiOlaoluwa/e56ad1b5478dc96a8c45232d8c37956b to your computer and use it in GitHub Desktop.
# Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
# e.g. [[1,2,[3]],4] -> [1,2,3,4].
# SOLUTION
class Array
def flatten_array(number = nil)
number ? multiple_flatten(self, number) : recursive_flatten(self)
end
private
def recursive_flatten(array, results = [])
array.each do |element|
if element.class == Array
recursive_flatten(element, results)
else
next unless element.is_a? Integer
results << element
end
end
results
end
def multiple_flatten(array, number)
count = 0
arr = array
until count >= number
arr = single_flatten(arr)
count += 1
end
arr
end
def single_flatten(array)
results = []
array.each do |element|
if element.class == Array
element.each { |value| results << value }
else
next unless element.is_a? Integer
results << element
end
end
results
end
end
# p [1, 2, [3, [4, 5]], 6, [7, 8], 9].flatten_array #=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
# p [1, 2, [3, [4, 5]], 6, [7, 8], 9].flatten_array(1) #=> [1, 2, 3, [4, 5], 6, 7, 8, 9]
# p [].flatten_array #=> []
# p [1, 2, 3, 4].flatten_array #=> [1, 2, 3, 4]
# p [1, 2, [3, [4, 5, [6, 7]]], 8, [9, 10], 11].flatten_array(2) #=> [1, 2, 3, 4, 5, [6, 7], 8, 9, 10, 11]
# p [1, 2, [3, [4, 5, [6, 7]]], 8, [9, 10], 11].flatten_array(3) #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# p [1, 2, 3, 4, 'one', :sss].flatten_array(3) #=> [1, 2, 3, 4]
# RSpec Exception Test
RSpec. describe Array do
it 'flattens array' do
array = [1, 2, [3, [4, 5]], 6, [7, 8], 9]
array = array.flatten_array
expect(array).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9])
end
it 'flattens array at a given nesting level as an argument' do
array = [1, 2, [3, [4, 5]], 6, [7, 8], 9]
array = array.flatten_array(1)
expect(array).to eq([1, 2, 3, [4, 5], 6, 7, 8, 9])
end
it 'does not leave out any given nest level un-flattened' do
array = [1, 2, [3, [4, 5]], 6, [7, 8], 9]
array = array.flatten_array
expect(array).not_to eq([1, 2, 3, [4, 5], 6, 7, 8, 9])
end
it 'returns empty Array' do
array = []
array = array.flatten_array
expect(array).to be_empty
end
it 'must be an instance of Array' do
array = [1, 2, 3, 4]
array = array.flatten_array
expect(array).to be_an_instance_of(Array)
end
it 'removes string and symbols from the array and flattens the array' do
array = [1, 2, 3, 4, 'one', :sss]
array = array.flatten_array
expect(array).to eq([1, 2, 3, 4])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment