Skip to content

Instantly share code, notes, and snippets.

@yanguango
Created December 10, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanguango/fb2c78f3386040d9f1f6 to your computer and use it in GitHub Desktop.
Save yanguango/fb2c78f3386040d9f1f6 to your computer and use it in GitHub Desktop.
Flat Array
def flat(nested)
return nil if nested.nil?
res = []
dfs(nested, res)
return res
end
# use DFS to search all integers
def dfs(item, res)
if !item.is_a?(Array)
res << item
else
item.each {|i| dfs(i, res)}
end
end
require './flat'
require 'minitest'
require 'minitest/autorun'
class FlatTest < Minitest::Test
def test_nil
assert_equal flat(nil), nil
end
def test_empty
assert_equal flat([]), []
end
def test_nested_empty
array = [[], [], [[]]]
assert_equal flat(array), []
end
def test_not_nested
array = [1, 2, 3, 4]
res = [1, 2, 3, 4]
assert_equal array, res
end
def test_nested
array = [[1, 2, [3]], 4]
res = [1, 2, 3, 4]
assert_equal flat(array), res
end
def test_nested_include_nil
array = [[1, 2, [nil]], 4]
res = [1, 2, nil, 4]
assert_equal flat(array), res
end
end
source 'https://rubygems.org'
group :test do
gem 'minitest'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment