Created
September 29, 2015 11:35
-
-
Save ilatif/3e434edbe379aed282df 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]
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 | |
# ArrayFlattener provides a method to flat nested array. | |
# For example, it can turn an array like [1, 2 [3, 4]] to [1, 2, 3, 4] | |
# Class method that can be called on ArrayFlattener that will convert nested array into flat array | |
def self.flatten(nested_array) | |
return [] if nested_array.length == 0 | |
self._flatten(nested_array, []) | |
end | |
private | |
# Private method that is doing main work by recursively iterating over any nested array found | |
def self._flatten(nested_array, flat_array) | |
nested_array.each do |elem| | |
if (elem.is_a?(Array)) | |
_flatten(elem, flat_array) | |
else | |
flat_array << elem | |
end | |
end | |
flat_array | |
end | |
end |
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
require "array_flattener" | |
RSpec.describe ArrayFlattener do | |
context "when array is empty" do | |
it "returns empty array without performing any operations" do | |
flat_array = ArrayFlattener.flatten([]) | |
expect(flat_array).to eq([]) | |
end | |
end | |
context "when array have items" do | |
it "flats single 1 level nested array" do | |
flat_array = ArrayFlattener.flatten([1,2,[3, 4]]) | |
expect(flat_array).to eq([1, 2, 3, 4]) | |
end | |
it "flats multiple 1 level nested array" do | |
flat_array = ArrayFlattener.flatten([[1, 2, 3], 4, [5, 6]]) | |
expect(flat_array).to eq([1, 2, 3, 4, 5, 6]) | |
end | |
it "flats single 2 level nested array" do | |
flat_array = ArrayFlattener.flatten([[1,2,[3]],4]) | |
expect(flat_array).to eq([1, 2, 3, 4]) | |
end | |
it "flats multiple 2 level nested array" do | |
flat_array = ArrayFlattener.flatten([[1, 2, [3], 4, 5], [6, 7, [8,9]]]) | |
expect(flat_array).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
end | |
it "flats nested array having elements like Hash" do | |
flat_array = ArrayFlattener.flatten([1, 2, [3, 4], {key1: 1, key2: 2}]) | |
expect(flat_array).to eq([1, 2, 3, 4, {key1: 1, key2: 2}]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment