Skip to content

Instantly share code, notes, and snippets.

@ashwinvidiyala
Created April 8, 2018 22:25
Show Gist options
  • Save ashwinvidiyala/6718d6460f095912441b09ef2ac09ada to your computer and use it in GitHub Desktop.
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
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
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
@ashwinvidiyala
Copy link
Author

Please reach out to me if you need any clarification about my code: [email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment