Skip to content

Instantly share code, notes, and snippets.

@bhenderson
Last active November 20, 2017 21:05
Show Gist options
  • Save bhenderson/d9196d3faf94bd4f74adb3a98fb30fe7 to your computer and use it in GitHub Desktop.
Save bhenderson/d9196d3faf94bd4f74adb3a98fb30fe7 to your computer and use it in GitHub Desktop.
require 'minitest/autorun'
##
# flatten takes an array of arbitrarily nested arrays of integers and returns a flattened array.
# Alternatively, if a block is given, the flattened version of the items is yielded
#
# :call-seq:
# flatten([[1,2,[3]],4]) -> [1,2,3,4]
#
# flatten([[1,2,[3]],4], &block) yields 1, 2, 3, 4
def flatten(arr)
if block_given?
if arr.is_a?(Array)
arr.each do |item|
flatten(item, &Proc.new)
end
else
yield arr
end
return
end
res = []
flatten(arr) do |item|
res << item
end
res
end
class ArrayFlattenerTest < Minitest::Test
def test_empty
assert_equal [], flatten([])
end
def test_already_flat
assert_equal [1,2,3], flatten([1,2,3])
end
def test_simple
assert_equal [1,2,3], flatten([1,[2,3]])
end
def test_sample
assert_equal [1,2,3,4], flatten([[1,2,[3]],4])
end
def test_complex
arr = [
[1],
[2, [3,4]],
[[[5,6,[7]]]]
]
assert_equal [1,2,3,4,5,6,7], flatten(arr)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment