Created
September 25, 2019 00:50
-
-
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."
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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