Skip to content

Instantly share code, notes, and snippets.

@drhuffman12
Last active May 30, 2019 00:00
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 drhuffman12/370889366be468efb6676220dc9d5dd3 to your computer and use it in GitHub Desktop.
Save drhuffman12/370889366be468efb6676220dc9d5dd3 to your computer and use it in GitHub Desktop.
Example code to flatten an array of arbitrarily nested arrays of integers into a flat array of integers (w/out language-provided array flatteners like Ruby's Array#flatten).
# PURPOSE:
#
# 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].
#
# Your solution should be a link to a gist on gist.github.com with your implementation.
#
# When writing this code, you can use any language you're comfortable with. The code must be well tested and documented.
# Please include unit tests and any documentation you feel is necessary. In general, treat the quality of the code as
# if it was ready to ship to production.
#
# Try to avoid using language defined methods like Ruby's Array#flatten.
#
# For a Gemified version, see: https://github.com/drhuffman12/example_long_hand_array_flattener
#
module ArrayUtils
class ArrayFlattenerError < StandardError; end
# (Verbose) Utility class to flatten an array
class ArrayFlattener
# Returns a flattened version of the given array
def self.run(array)
flattened_array = []
array.each do |element|
if element.is_a?(Array)
sub_flattened_array = run(element)
sub_flattened_array.each {|sub_flattened_elem| flattened_array << sub_flattened_elem}
elsif element.is_a?(Integer)
flattened_array << element
else
raise ArrayFlattenerError.new("ERROR: Non-Integer element in given array")
end
end
flattened_array
end
end
# Class to test ArrayFlattener
class ArrayFlattenerTest
def self.test_given_array_is_flattened(given,expected)
actual = ArrayFlattener.run(given)
{succeeded: (expected == actual), given: given, expected: expected, actual: actual}
rescue ArrayFlattenerError => ex
{succeeded: false, given: given, expected: expected, error: ex}
end
def self.run
given = [[1,2,[3]],4]
expected = [1,2,3,4]
# # Or try.. other valid example
# given = [[1,2,[3]],4,[5,[6,7]]]
# expected = [1,2,3,4,5,6,7]
# # Or try.. force failure via typo of '4000' instead of '4'
# given = [[1,2,[3]],4000]
# expected = [1,2,3,4]
# # Or try.. exception handling
# given = [[1,2,[3]],4,'errors']
# expected = [1,2,3,4]
results = test_given_array_is_flattened(given,expected)
message = results[:succeeded] ? "Test Passes" : "Test Fails; #{results}"
puts message
end
end
end
ArrayUtils::ArrayFlattenerTest.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment