Created
April 8, 2018 22:25
-
-
Save ashwinvidiyala/6718d6460f095912441b09ef2ac09ada 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
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 Flatten | |
def self.flatten input, answer = [] | |
# Function is called recursively if element of input is an Array. | |
# If element is not an Array, it is pushed to answer. | |
input.each do |element| | |
element.is_a?(Array) ? self.flatten(element, answer) : answer << element | |
end | |
answer | |
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 'minitest/autorun' | |
require_relative 'flatten' | |
class FlattenTest < Minitest::Test | |
def test_flatten_simple | |
assert_equal [1,2,3,4], Flatten.flatten([[1,2,[3]],4]) | |
end | |
def test_flatten_intermediate | |
assert_equal [1,2,3,4], Flatten.flatten([[[[1,[2],[3]],4]]]) | |
end | |
def test_flatten_complex | |
assert_equal [1,2,3,4,5,6,7], Flatten.flatten([[[[1,2],3,4,5],6],7]) | |
end | |
def test_flatten_monster | |
assert_equal [19,57,1,69,0], Flatten.flatten([[[19],[57]],[[1],[[69],[0]]]]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please reach out to me if you need any clarification about my code: [email protected]