Skip to content

Instantly share code, notes, and snippets.

@entrity
Created September 25, 2019 00:50
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 entrity/4107a4225f85cb9100d88970a5fbb15b to your computer and use it in GitHub Desktop.
Save entrity/4107a4225f85cb9100d88970a5fbb15b to your computer and use it in GitHub Desktop.
A coding demo for a job application at Theorem, LLC. "Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers."
# Here's a function to 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].
#
# This was written for Ruby 2
#
# Invoke this function by passing it the array to be flattened in the
# "input" argument and leaving the "output" argument nil.
#
# E.g.
# >> recursive_flatten([[1,2,[3]],4])
def recursive_flatten(input, output=nil)
output ||= []
for value in input
if value.is_a? Integer
output << value
elsif value.is_a? Array
recursive_flatten(value, output)
else
raise 'Error. All array items must be Integers or Arrays. Got %s' % value.class.name
end
end
output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment